ドラフト ECMA-262 / 2025年7月24日
ECMAScript® 2026 言語仕様
はじめに
このEcma規格は、ECMAScript
2026言語を定義します。これはECMAScript言語仕様の第17版です。1997年の初版発行以来、ECMAScriptは世界で最も広く使われている汎用プログラミング言語のひとつに成長しました。主にウェブブラウザに組み込まれている言語として知られていますが、サーバーや組み込みアプリケーションにも広く採用されています。
ECMAScriptは、主にJavaScript(Netscape)やJScript(Microsoft)など、いくつかの元技術に基づいています。この言語はBrendan
EichによってNetscapeで発明され、同社のNavigator 2.0ブラウザで初めて登場しました。その後、Netscapeのすべてのブラウザと、MicrosoftのInternet Explorer
3.0以降のすべてのブラウザに実装されています。
ECMAScript言語仕様の開発は1996年11月に始まりました。このEcma規格の初版は、1997年6月のEcma総会で採択されました。
そのEcma規格はISO/IEC JTC 1に迅速な審査手続きで提出され、1998年4月に国際規格ISO/IEC 16262として承認されました。1998年6月のEcma総会では、ISO/IEC
16262と完全に一致させるため、ECMA-262第2版が承認されました。第1版と第2版の変更点は編集上のものです。
第3版では、強力な正規表現、より優れた文字列操作、新しい制御文、try/catch例外処理、エラー定義の厳格化、数値出力の書式指定、将来的な言語拡張を見据えた小規模な変更などが導入されました。ECMAScript標準の第3版は、1999年12月のEcma総会で採択され、2002年6月にISO/IEC
16262:2002として発行されました。
第3版発行後、ECMAScriptはWorld Wide
Webとともに爆発的な普及を遂げ、ほぼすべてのウェブブラウザが対応するプログラミング言語となりました。第4版の開発も進みましたが、完成には至らず正式な第4版として発行されませんでした。ただし、その一部は第6版の開発に取り込まれています。
ECMAScript第5版(ECMA-262第5版として発行)は、ブラウザ実装で一般的となった言語仕様の事実上の解釈を明文化し、第3版発行以降に登場した新機能も追加しました。これらには、アクセサプロパティ 、オブジェクトの反射的生成・検査、プロパティ属性のプログラム制御、配列操作関数の追加、JSONオブジェクトのエンコード形式対応、エラー検出とプログラムセキュリティを強化するstrict
modeなどが含まれます。第5版は2009年12月のEcma総会で採択されました。
第5版はISO/IEC JTC 1に迅速な審査手続きで提出され、国際規格ISO/IEC 16262:2011として承認されました。ECMAScript標準の第5.1版は細かな修正を取り入れており、ISO/IEC
16262:2011と同じ内容です。第5.1版は2011年6月のEcma総会で採択されました。
第6版の本格的な開発は2009年に始まりましたが、これは第3版(1999年発行)以降に行われてきたさまざまな実験や言語拡張設計の集大成です。この版の目標には、大規模アプリケーションやライブラリの開発、他言語のコンパイル先としてのECMAScript利用の強化が含まれていました。主な拡張としては、モジュール、クラス宣言、レキシカルブロックスコープ、イテレータ とジェネレータ、非同期プログラミング用のプロミス、分割代入、適切な末尾呼び出しなどがあります。ECMAScript組み込みライブラリも拡張され、マップやセット、バイナリ数値値の配列、文字列・正規表現のUnicode補助文字対応などが追加されました。組み込みはサブクラス化で拡張可能となり、第6版は定期的かつ漸進的な言語・ライブラリエンハンスの基盤を提供します。第6版は2015年6月の総会で採択されました。
ECMAScript 2016は、Ecma TC39の新しい年次リリース体制と公開開発プロセスの下でリリースされた最初の版です。ECMAScript
2015のソースをプレーンテキストに変換した文書が、GitHub上での開発ベースとして使われました。この標準の開発期間中、数百件のプルリクエストやイシューが提出され、何千ものバグ修正、編集修正、その他の改善が行われました。また、Ecmarkup、Ecmarkdown、Grammarkdownなどのソフトウェアツールも開発されました。ES2016では新しいべき乗演算子やArray.prototypeのincludesメソッドが追加されました。
ECMAScript 2017では、Async Functions、Shared Memory、Atomicsの導入、その他小規模な言語・ライブラリの拡張、バグ修正、編集更新が行われました。Async
FunctionsはPromiseを返す関数のための構文を提供し、非同期プログラミング体験を向上させました。Shared
MemoryとAtomicsは、並列CPU上でも確定した実行順序を維持できる原子的操作を使って複数エージェント 間で通信できる新しいメモリモデル を導入しました。さらに、Objectの新しい静的メソッドObject.values、Object.entries、Object.getOwnPropertyDescriptorsも追加されました。
ECMAScript 2018では、非同期イテレータ プロトコルおよび非同期ジェネレータによる非同期反復処理が導入されました。また、正規表現に4つの新機能(dotAllフラグ、名前付きキャプチャグループ、Unicodeプロパティエスケープ、後方参照)が追加され、オブジェクトのrest/spreadプロパティも追加されました。
ECMAScript
2019では、配列の平坦化のためのflatおよびflatMap(Array.prototype)、Object.entriesの戻り値を直接新しいオブジェクトに変換するObject.fromEntries、より適切な名称のtrimStartとtrimEnd(String.prototype、従来のtrimLeft/trimRightの代替)、その他細かな構文・意味論の更新が導入されました。構文の更新にはcatchバインディングパラメータの省略や、JSONとの整合性のために文字列リテラルでU+2028(LINE
SEPARATOR)とU+2029(PARAGRAPH
SEPARATOR)を許可することなどがあります。そのほか、Array.prototype.sortの安定化、JSON.stringifyのUTF-8出力標準化、Function.prototype.toStringの仕様明確化などが行われました。
ECMAScript
2020(第11版)では、グローバル正規表現による全マッチオブジェクトのイテレータを生成するmatchAllメソッド(Strings)、動的な指定子でモジュールを非同期インポートするimport()構文、任意精度整数用の新しい数値プリミティブBigInt、短絡しない新しいPromise合成手法Promise.allSettled、グローバルthis値への統一的アクセスglobalThis、モジュール内で使うexport * as ns from 'module'構文、for-in列挙順の標準化、モジュールに関するコンテキスト情報を持つimport.meta(ホスト が設定)、nullish値(undefined やnull )操作を改善するnullish
coalescing演算子・optional chaining演算子などが導入されました。
ECMAScript
2021(第12版)では、Strings用のreplaceAllメソッド、Promise合成のPromise.any(入力値のいずれかがfulfilledになると短絡)、複数のエラーを同時に表現する新しいError型AggregateError、論理代入演算子(??=、&&=、||=)、ガベージコレクションから保護せずにターゲットオブジェクトを参照するWeakRef、ターゲットオブジェクトのガベージコレクション時にクリーンアップ操作を管理するFinalizationRegistry、数値リテラルの区切り文字(1_000)、Array.prototype.sortの仕様厳密化(実装定義
ソート順 のケース減少)などがあります。
ECMAScript 2022(第13版)では、モジュールのトップレベルでawaitを使えるようになり(キーワード )、新しいクラス要素(public/privateインスタンスフィールド、public/private静的フィールド、privateインスタンスメソッド・アクセサ、private静的メソッド・アクセサ)、クラス内staticブロック(クラス単位の評価初期化)、#x in obj構文(オブジェクトのprivateフィールドの存在判定)、正規表現のマッチインデックス(/dフラグ)、Errorオブジェクトのcauseプロパティ(エラーの因果関係記録)、Strings/Arrays/TypedArrays 用のatメソッド(相対インデックス)、Object.hasOwn(Object.prototype.hasOwnPropertyの便利な代替)などが導入されました。
ECMAScript
2023(第14版)では、Array.prototypeとTypedArray.prototypeにtoSorted、toReversed、with、findLast、findLastIndexが追加され、Array.prototypeにはtoSplicedが追加されました。また、実行可能なECMAScriptファイルのためにファイル先頭の#!コメント対応、ほとんどのSymbolをweakコレクションのキーとして利用可能になりました。
ECMAScript
2024(第15版)では、ArrayBufferやSharedArrayBufferのリサイズ・転送機能、文字列集合処理に便利な新しいRegExpの/vフラグ、Promise構築を容易にするPromise.withResolvers、データ集計用のObject.groupByおよびMap.groupBy、共有メモリの非同期変更待機用Atomics.waitAsync、Unicodeの正当性チェックと修正用String.prototype.isWellFormed・String.prototype.toWellFormedなどが追加されました。
ECMAScript 2025(第16版)では、イテレータ操作のための新しいグローバルIterator(イテレータ 用の静的・プロトタイプメソッド)、Set.prototype用のセット操作メソッド、JSONモジュールのインポートとインポート属性宣言構文、正規表現で安全に使えるよう文字列エスケープするRegExp.escapeメソッド、正規表現修飾フラグのインライン制御構文、関数のPromise化のためのPromise.tryメソッド、そして新しいFloat16Array(TypedArray の一種)、関連するDataView.prototype.getFloat16・DataView.prototype.setFloat16・Math.f16roundメソッドが追加されました。
Ecma
TC39には多くの団体を代表する何十人もの個人が本版および過去の版の発展に大きく貢献しています。さらに、TC39のECMAScript活動を支える活発なコミュニティが生まれ、数多くのドラフトのレビュー、何千件ものバグ報告、実装実験、テストスイートの提供、世界中の開発者への教育が行われています。残念ながら、貢献者全員を特定し、記載することは不可能です。
Allen Wirfs-Brock
ECMA-262, プロジェクトエディター, 第6版
Brian Terlson
ECMA-262, プロジェクトエディター, 第7〜10版
Jordan Harband
ECMA-262, プロジェクトエディター, 第10〜12版
Shu-yu Guo
ECMA-262, プロジェクトエディター, 第12〜16版
Michael Ficarra
ECMA-262, プロジェクトエディター, 第12〜16版
Kevin Gibbons
ECMA-262, プロジェクトエディター, 第12〜16版
1 範囲
本規格はECMAScript 2026汎用プログラミング言語を定義します。
2 適合性
ECMAScriptの適合実装は、本仕様で記述されているすべての型、値、オブジェクト、プロパティ、関数、プログラム構文および意味論を提供し、サポートしなければなりません。
ECMAScriptの適合実装は、入力されたソーステキストをUnicode標準およびISO/IEC 10646の最新バージョンに準拠して解釈しなければなりません。
異なる言語や国の言語的・文化的慣習に適応するプログラムをサポートするアプリケーションプログラミングインターフェース(API)を提供するECMAScriptの適合実装は、本仕様と互換性のある最新のECMA-402版で定義されるインターフェースを実装しなければなりません。
ECMAScriptの適合実装は、本仕様で記述されている内容以外にも、追加の型、値、オブジェクト、プロパティ、関数を提供してもかまいません。特に、適合実装は本仕様で記載されていないプロパティや、そのプロパティの値を、本仕様で記述されているオブジェクトに対して提供してもかまいません。
ECMAScriptの適合実装は、本仕様で記載されていないプログラム構文や正規表現構文をサポートしてもかまいません。特に、適合実装は本仕様の予約語 に記載されている「将来の予約語」を用いたプログラム構文をサポートすることができます(12.7.2 参照)。
ECMAScriptの適合実装は、本仕様の17.1 で禁じられている拡張(Forbidden Extension)を実装してはなりません。
ECMAScriptの適合実装は、実装定義 、実装近似 、またはホスト定義 でない機能を再定義してはなりません。
ECMAScriptの適合実装は、規範的オプション (Normative
Optional)サブ句を実装するかどうかを選択できます。規範的オプションの動作を実装する場合は、包含している規範的オプション句内のすべての動作を実装しなければなりません。規範的オプション句は、本仕様で「Normative
Optional」と表示された色付きのボックスで示されます(下記参照)。
2.1 規範的オプション句の見出し例
句の内容例。
ECMAScriptの適合実装は、規範的オプションとしてもマークされていない限り、レガシー (Legacy)サブ句を実装しなければなりません。レガシーサブ句内で規定されている言語機能や動作には、ひとつ以上の望ましくない特徴がありますが、既存アプリケーションでの利用が継続されているため、本仕様から削除できません。これらの機能はECMAScript言語の中核部分とはみなされません。プログラマーは新しいECMAScriptコードを書く際、これらの機能や動作の利用や存在を前提にすべきではありません。
2.2 レガシー句の見出し例
句の内容例。
2.3 レガシー規範的オプション句の見出し例
句の内容例。
3 規範参照文献
以下の参照文書は、本書の適用に不可欠です。日付付き参照については、引用された版のみが適用されます。日付なし参照については、参照文書の最新版(改訂および修正を含む)が適用されます。
IEEE
754-2019 、IEEE 浮動小数点算術標準 。
Unicode標準。
https://unicode.org/versions/latest
ISO/IEC 10646, 情報技術 ― ユニバーサル多オクテット符号化文字集合 (UCS)
と改訂1:2005、改訂2:2006、改訂3:2008、改訂4:2008、追加改訂・正誤表、または後継。
ECMA-402, ECMAScript国際化API仕様 、本仕様の版に対応する年次版。
https://www.ecma-international.org/publications-and-standards/standards/ecma-402/
ECMA-404, JSONデータ交換フォーマット 。
https://www.ecma-international.org/publications-and-standards/standards/ecma-404/
4 概要
この節はECMAScript言語の非規範的な概要を含みます。
ECMAScriptは、ホスト環境 内で計算を行い、計算オブジェクトを操作するためのオブジェクト指向プログラミング言語です。ここで定義されるECMAScriptは、計算上自己完結することを意図していません。実際、本仕様には外部データの入力や計算結果の出力に関する規定がありません。代わりに、ECMAScriptプログラムの計算環境が、本仕様で記述されているオブジェクトやその他の機能だけでなく、環境固有のオブジェクトも提供することが想定されています。これらのオブジェクトの説明や動作は本仕様の範囲外ですが、特定のプロパティへのアクセスや関数呼び出しがECMAScriptプログラムから可能であることが示されています。
ECMAScriptは当初スクリプト言語として設計されましたが、現在では汎用プログラミング言語として広く使われています。スクリプト言語 とは、既存システムの機能を操作・カスタマイズ・自動化するためのプログラミング言語です。こうしたシステムでは、ユーザーインターフェースを通じて有用な機能がすでに利用可能であり、スクリプト言語はその機能をプログラム制御に公開する手段となります。このように、既存システムはスクリプト言語の機能を補完するホスト環境 のオブジェクトや機能を提供します。スクリプト言語は、専門・非専門いずれのプログラマーにも利用されることを想定しています。
ECMAScriptは当初Webスクリプト言語 として設計され、ブラウザでWebページを動的にし、Webベースのクライアントサーバーアーキテクチャの一部としてサーバ計算を行う仕組みを提供していました。現在、ECMAScriptは様々なホスト環境 のコアスクリプト機能として利用されています。そのため、コア言語は特定のホスト環境 とは切り離して本書で規定されています。
ECMAScriptの利用は単純なスクリプトを超え、さまざまな環境や規模で多岐にわたるプログラミング業務に使われています。利用拡大に伴い、ECMAScriptが提供する機能や設備も拡充されました。現在、ECMAScriptは完全な機能を備えた汎用プログラミング言語となっています。
4.1 Webスクリプティング
ウェブブラウザは、クライアントサイド計算のためのECMAScriptホスト環境 を提供します。これにはウィンドウ、メニュー、ポップアップ、ダイアログボックス、テキストエリア、アンカー、フレーム、履歴、クッキー、入出力などを表すオブジェクトが含まれます。また、ホスト環境 は、フォーカス変更、ページや画像の読み込み・アンロード・エラー・中断・選択・フォーム送信・マウス操作などのイベントにスクリプトコードを関連付ける手段も提供します。スクリプトコードはHTML内に記述され、表示されるページはユーザーインターフェース要素と固定・計算済みのテキストや画像の組み合わせです。スクリプトコードはユーザー操作に反応し、メインプログラムは不要です。
ウェブサーバは、サーバサイド計算のための別のホスト環境 を提供します。これにはリクエスト・クライアント・ファイルを表すオブジェクトや、データのロック・共有機構が含まれます。ブラウザ側とサーバ側のスクリプトを組み合わせることで、クライアントとサーバ間で計算を分散し、Webベースアプリケーションのユーザーインターフェースをカスタマイズできます。
ECMAScriptをサポートする各Webブラウザとサーバは、それぞれ独自のホスト環境 を提供し、ECMAScript実行環境を完成させます。
4.2 ホストと実装
ECMAScriptをホスト環境 に統合しやすくするために、本仕様では特定の機能(例:抽象操作 )の定義を、全体または一部を外部ソースに委ねています。編集上、本仕様は以下の種類の委譲を区別しています。
実装 は、付録D で列挙された機能や、実装定義 または実装近似 とマークされた機能をさらに定義する外部ソースです。非公式には、実装は特定のWebブラウザなどの具体的な成果物を指します。
実装定義 機能は、定義を外部ソースに委ねるものです。本仕様は特定の動作について推奨を行わず、適合実装は本仕様で定められた制約内で任意の動作を選択できます。
実装近似 機能は、定義を外部ソースに委ねつつ、理想的な動作を推奨するものです。適合実装は制約内で任意の動作を選択できますが、理想的な動作に近づけることが奨励されます。例えば、Math.exp などの数学操作は実装近似 です。
ホスト は、付録D に記載された機能のみをさらに定義する外部ソースであり、その他の実装定義 や実装近似 機能は定義しません。非公式には、ホスト は、付録D を通じて本仕様と同じ方法でインターフェースするすべてのWebブラウザの集合などを指します。ホスト はWHATWG HTML(https://html.spec.whatwg.org/ )などの外部仕様であることが多いです。つまり、ホスト定義 機能は外部仕様でさらに定義される場合が多いです。
ホストフック は、全体または一部が外部ソースで定義される抽象操作です。すべてのホストフック は付録D に列挙されなければなりません。ホストフック は、以下の要件を満たす必要があります:
ホスト定義 機能は、定義を外部ソースに委ねるもので、付録D に列挙されるものです。ホスト でない実装も、ホスト定義 機能の定義を提供できます。
ホスト環境 は、すべてのホスト定義 機能の定義選択です。ホスト環境 は、ホスト定義 プロパティとして、グローバルオブジェクト から入力取得や出力提供を可能にするオブジェクトや関数などを含むことが一般的です。
本仕様は、常に最も具体的な用語を使う編集慣例に従います。例えば、機能がホスト定義 であれば、実装定義 として参照すべきではありません。
ホスト と実装の両方が、本仕様で定義される言語型、仕様型、抽象操作 、文法生成規則、組み込みオブジェクト、組み込みシンボルを通じて本仕様とインターフェースできます。
4.3 ECMAScript概要
以下はECMAScriptの非公式な概要です。言語のすべての部分が説明されているわけではありません。この概要は規格本体の一部ではありません。
ECMAScriptはオブジェクトベースです。基本的な言語機能やホスト 機能はオブジェクトによって提供され、ECMAScriptプログラムは通信するオブジェクトの集合体です。ECMAScriptにおいて、オブジェクト は0個以上のプロパティ の集合であり、各プロパティにはその利用方法を決定する属性 があります。例えば、プロパティのWritable属性がfalse に設定されている場合、実行されたECMAScriptコードがそのプロパティに異なる値を代入しようとしても失敗します。プロパティは他のオブジェクト、プリミティブ値 、または関数 を保持するコンテナです。プリミティブ値は以下の組み込み型のいずれかのメンバーです:Undefined 、Null 、Boolean 、Number 、BigInt 、String 、Symbol 。オブジェクトは組み込み型Object のメンバーです。関数は呼び出し可能なオブジェクトです。オブジェクトのプロパティを通じて関連付けられた関数はメソッド と呼ばれます。
ECMAScriptは、ECMAScriptエンティティの定義を補完する組み込みオブジェクト の集合も定義します。これらの組み込みオブジェクトには、グローバルオブジェクト 、言語の実行時意味論 に不可欠なObject、Function、Boolean、Symbol、各種Errorオブジェクト、数値値の表現・操作用Math、Number、Date、テキスト処理用のString、RegExp、値のインデックス付きコレクションであるArrayと9種類のTyped
Array(要素が特定の数値データ表現を持つ)、キー付きコレクションのMap、Setオブジェクト、構造化データ用のJSONオブジェクト、ArrayBuffer、SharedArrayBuffer、DataView、制御抽象のためのジェネレータ関数やPromiseオブジェクト、リフレクション用のProxyやReflectなどが含まれます。
ECMAScriptは組み込み演算子 も定義しています。ECMAScriptの演算子には、様々な単項演算、乗算演算子、加算演算子、ビットシフト演算子、関係演算子、等価演算子、2項ビット演算子、2項論理演算子、代入演算子、カンマ演算子などがあります。
大規模なECMAScriptプログラムはモジュール によってサポートされており、プログラムを複数の文や宣言の列に分割できます。各モジュールは、他のモジュールから提供される必要がある宣言、および他のモジュールで利用可能な自身の宣言を明示的に識別します。
ECMAScriptの構文は意図的にJavaの構文に似せてあります。ECMAScriptの構文は、使いやすいスクリプト言語として機能するよう緩和されています。例えば、変数は型宣言が不要であり、プロパティにも型は関連付けられず、定義された関数は呼び出しより前に宣言が現れている必要はありません。
4.3.1 オブジェクト
ECMAScriptはクラス定義の構文を含みますが、ECMAScriptオブジェクトはC++、Smalltalk、Javaのように本質的にクラスベースではありません。代わりに、オブジェクトはリテラル記法やコンストラクタ によって様々な方法で生成できます。コンストラクタはオブジェクトを生成し、初期値をプロパティに代入して初期化するコードを実行します。各コンストラクタ は"prototype" という名前のプロパティを持ち、プロトタイプベースの継承 と共有プロパティ を実現します。オブジェクトはnew 式でコンストラクタ を使用して作成されます。例えば、new Date(2009, 11)は新しいDateオブジェクトを生成します。new を使わずにコンストラクタ を呼び出すと、その結果はコンストラクタ 次第で異なります。例えば、Date()はオブジェクトではなく現在の日時の文字列を生成します。
コンストラクタ で生成されたすべてのオブジェクトは、暗黙の参照(オブジェクトのプロトタイプ )を自身のコンストラクタ の"prototype" プロパティ値に持ちます。さらに、プロトタイプは非null のプロトタイプへの暗黙の参照を持つことがあり、これがプロトタイプチェーン です。オブジェクトのプロパティに参照が行われると、その参照はプロトタイプチェーン上でその名前のプロパティを持つ最初のオブジェクトのプロパティに向けられます。つまり、まず直接指定されたオブジェクトを調べ、そのオブジェクトに名前付きプロパティがあればそれが参照先です。なければそのオブジェクトのプロトタイプを次に調べ、以降も同様です。
図1: オブジェクト/プロトタイプ関係
クラスベースのオブジェクト指向言語では、一般に、状態はインスタンスが保持し、メソッドはクラスが保持し、継承は構造と振る舞いのみです。ECMAScriptでは、状態もメソッドもオブジェクトが保持し、構造・振る舞い・状態のすべてが継承されます。
プロトタイプが特定のプロパティを持っていて、そのプロパティを直接持たないすべてのオブジェクトは、そのプロパティと値を共有します。図1はこの関係を示しています。
CF はコンストラクタ (かつオブジェクト)です。5つのオブジェクト(cf1 、cf2 、cf3 、cf4 、cf5 )がnew式で生成されています。各オブジェクトは"q1" と"q2" というプロパティを持ちます。破線は暗黙のプロトタイプ関係を表し、例えばcf3 のプロトタイプはCFp です。コンストラクタ CF 自体は、"P1" と"P2" という2つのプロパティを持ちますが、これらはCFp 、cf1 、cf2 、cf3 、cf4 、cf5 からは見えません。CFp の"CFP1" プロパティは、cf1 、cf2 、cf3 、cf4 、cf5 (CF は除く)で共有されます。また、CFp の暗黙のプロトタイプチェーン上で"q1" 、"q2" 、"CFP1" 以外のプロパティも共有されます。CF とCFp の間には暗黙のプロトタイプリンクはありません。
ほとんどのクラスベースオブジェクト言語と異なり、オブジェクトには値を代入することで動的にプロパティを追加できます。つまり、コンストラクタ は、生成されるオブジェクトのすべてまたは一部のプロパティに名前や値の代入を必須としません。上図の場合、CFp に新たな値を代入することで、cf1 、cf2 、cf3 、cf4 、cf5 に新しい共有プロパティを追加できます。
ECMAScriptオブジェクトは本質的にクラスベースではありませんが、共通パターンのコンストラクタ 関数、プロトタイプオブジェクト、メソッドに基づいてクラス的な抽象を定義するのが便利です。ECMAScriptの組み込みオブジェクト自身もこのようなクラス的パターンに従っています。ECMAScript
2015以降、ECMAScript言語には組み込みオブジェクトと同様のクラス的抽象パターンに準拠したオブジェクトを簡潔に定義可能なクラス定義構文が追加されています。
4.3.2 ECMAScriptの厳格なバリアント
ECMAScript言語は、言語の一部機能の利用を制限したいユーザーがいる可能性を認識しています。これは、セキュリティの観点、エラーを招きやすい機能の回避、エラー検出の強化、その他ユーザー独自の理由によるものです。この可能性をサポートするために、ECMAScriptは言語の厳格なバリアントを定義しています。厳格なバリアントでは、通常のECMAScript言語から特定の構文的・意味的機能を除外し、一部機能の詳細な意味論を変更します。厳格なバリアントでは、非厳格な言語形式ではエラーとされない状況でも、エラー例外をthrowして報告しなければならない追加のエラー条件も規定しています。
ECMAScriptの厳格なバリアントは、一般に言語のstrict mode (厳格モード)と呼ばれます。厳格モードの選択と構文・意味論の利用は、ECMAScriptソーステキスト 単位で明示的に行われます(11.2.2 参照)。厳格モードは構文ソーステキスト単位で選択されるため、その制限はそのユニット内で局所的にのみ適用されます。厳格モードは、複数のソーステキストユニット間で一貫して動作するECMAScriptの意味論の側面を制限・変更しません。完全なECMAScriptプログラムは、厳格モードと非厳格モードの両方のECMAScriptソーステキスト ユニットで構成される場合があります。この場合、厳格モードは実際に厳格モードソーステキストユニット内で定義されたコードが実行される場合にのみ適用されます。
本仕様に適合するために、ECMAScriptの実装は本仕様で定義された完全な非制限ECMAScript言語と厳格なバリアントの両方を実装しなければなりません。さらに、非制限モードと厳格モードのソーステキストユニットの組み合わせによる複合プログラムもサポートしなければなりません。
4.4 用語と定義
本書の目的において、以下の用語と定義が適用されます。
4.4.1 implementation-approximated
implementation-approximated
機能は、全体または一部が外部ソースによって定義されますが、本仕様に推奨される理想的な動作があります。
4.4.2 implementation-defined
implementation-defined
機能は、本仕様に対する外部ソースによって全体または一部が定義されます。
4.4.3 host-defined
implementation-defined と同じ
注
4.4.4 type
6 節で定義されるデータ値の集合
4.4.5 primitive value
型 Undefined、Null、Boolean、Number、BigInt、Symbol、String のいずれかのメンバー(6 節参照)
注
プリミティブ値は、言語実装の最下層レベルで直接表現されるデータです。
4.4.6 object
型 Object のメンバー
注
オブジェクトはプロパティの集合体であり、単一のプロトタイプオブジェクトを持ちます。プロトタイプは null であってもよいです。
4.4.7 constructor
オブジェクトを生成・初期化する function object
注
constructor の "prototype"
プロパティの値は、継承と共有プロパティの実装に使用されるプロトタイプオブジェクトです。
4.4.8 prototype
他のオブジェクトに共有プロパティを提供するオブジェクト
注
constructor
がオブジェクトを生成すると、そのオブジェクトはプロパティ参照解決のために暗黙的に constructor の "prototype"
プロパティを参照します。constructor の "prototype"
プロパティは、プログラム式 constructor .prototype
で参照でき、プロトタイプに追加されたプロパティは継承によりそのプロトタイプを共有するすべてのオブジェクトで共有されます。あるいは、Object.create
組み込み関数を使って明示的に指定したプロトタイプ付きの新しいオブジェクトを生成することもできます。
4.4.9 ordinary object
すべてのオブジェクトがサポートすべき本質的な内部メソッドに対してデフォルトの動作を持つオブジェクト
4.4.10 exotic object
本質的な内部メソッドのうち1つ以上についてデフォルトの動作を持たないオブジェクト
注
4.4.11 standard object
本仕様で意味論が定義されているオブジェクト
4.4.12 built-in object
ECMAScript実装によって規定・提供されるオブジェクト
注
標準の組み込みオブジェクトは本仕様で定義されています。ECMAScript実装は追加の組み込みオブジェクトを規定・提供してもかまいません。
4.4.13 undefined value
変数に値が代入されていない場合に使われるプリミティブ値
4.4.14 Undefined type
唯一の値が undefined である型
4.4.15 null value
いかなるオブジェクト値も意図的に存在しないことを表すプリミティブ値
4.4.16 Null type
唯一の値が null である型
4.4.17 Boolean value
Boolean type のメンバー
注
Boolean値は true と false の2つのみです。
4.4.18 Boolean type
プリミティブ値 true および false からなる型
4.4.19 Boolean object
標準組み込み Boolean constructor のインスタンスである Object type
のメンバー
注
Booleanオブジェクトは、Boolean constructor を new
式で使い、Boolean値を引数として生成されます。生成されたオブジェクトは内部スロットにBoolean値を保持します。BooleanオブジェクトはBoolean値に強制変換することができます。
4.4.20 String value
ゼロ以上の16ビット符号なし integer
値の有限 な順序付き列であるプリミティブ値
注
String値は String type
のメンバーです。列内の各 integer
値は通常、UTF-16テキストの16ビット単位を表します。ただし、ECMAScriptでは値に関して16ビット符号なし integer であること以外の制約や要件はありません。
4.4.21 String type
すべての可能なString値の集合
4.4.22 String object
標準組み込み String constructor のインスタンスである Object type
のメンバー
注
Stringオブジェクトは、String constructor を new
式で使い、String値を引数として生成されます。生成されたオブジェクトは内部スロットにString値を保持します。Stringオブジェクトは、String constructor
を関数として呼び出すことでString値に強制変換できます(22.1.1.1 )。
4.4.23 Number value
倍精度64ビットバイナリ形式 IEEE
754-2019 値に対応するプリミティブ値
注
Number値は Number type
のメンバーであり、数値を直接表現します。
4.4.24 Number type
すべての可能なNumber値の集合(NaN (非数)、+∞ 𝔽 (正の無限大)、-∞ 𝔽 (負の無限大)を含む)
4.4.25 Number object
標準組み込み Number constructor のインスタンスである Object type
のメンバー
注
Numberオブジェクトは、Number constructor を new
式で使い、Number値を引数として生成されます。生成されたオブジェクトは内部スロットにNumber値を保持します。Numberオブジェクトは、Number constructor
を関数として呼び出すことでNumber値に強制変換できます(21.1.1.1 )。
4.4.26 Infinity
正の無限大のNumber値
4.4.27 NaN
IEEE
754-2019 のNaN(非数)値であるNumber値
4.4.28 BigInt value
任意精度 integer
値に対応するプリミティブ値
4.4.29 BigInt type
すべての可能なBigInt値の集合
4.4.30 BigInt object
標準組み込み BigInt constructor のインスタンスである Object type
のメンバー
4.4.31 Symbol value
ユニークな、非Stringオブジェクト property key を表すプリミティブ値
4.4.32 Symbol type
すべての可能なSymbol値の集合
4.4.33 Symbol object
標準組み込み Symbol constructor のインスタンスである Object type
のメンバー
4.4.34 function
サブルーチンとして呼び出すことができる Object type のメンバー
注
関数はプロパティに加え、呼び出されたときの挙動を決定する実行コードと状態を持ちます。関数のコードはECMAScriptで記述されている場合とそうでない場合があります。
4.4.35 built-in function
関数である組み込みオブジェクト
注
組み込み関数の例:parseInt、Math.exp。ホスト や実装は、本仕様に記載されていない追加の組み込み関数を提供することがあります。
4.4.36 built-in constructor
constructor
である組み込み関数
注
組み込み constructor
の例:Object、Function。ホスト や実装は、本仕様に記載されていない追加の組み込み constructor
を提供することがあります。
4.4.37 property
キー(String値またはSymbol値)と値を関連付けるオブジェクトの一部
注
プロパティの形態によって、値はデータ値(プリミティブ値、オブジェクト、function
object )として直接表現される場合もあれば、アクセサ関数のペアによって間接的に表現される場合もあります。
4.4.38 method
プロパティの値である関数
注
関数がオブジェクトのメソッドとして呼び出されると、そのオブジェクトは関数に this 値として渡されます。
4.4.39 built-in method
組み込み関数であるメソッド
注
標準組み込みメソッドは本仕様で定義されています。ホスト や実装は、本仕様に記載されていない追加の組み込みメソッドを提供することがあります。
4.4.40 attribute
プロパティの特徴を定義する内部値
4.4.41 own property
オブジェクトが直接保持するプロパティ
4.4.42 inherited property
オブジェクト自身のプロパティではないが、そのオブジェクトのプロトタイプの(自身または継承された)プロパティであるプロパティ
4.5 本仕様書の構成
本仕様書の残りの部分は以下のように構成されています:
第5 節では、仕様全体で使用される記法上の規約を定義します。
第6 節から第10 節までは、ECMAScriptプログラムが動作する実行環境を定義します。
第11 節から第17 節までは、ECMAScriptプログラミング言語そのもの(構文的表現や全言語機能の実行意味論)を定義します。
第18 節から第28 節までは、ECMAScript標準ライブラリを定義します。これらの節には、ECMAScriptプログラムが実行時に利用可能なすべての標準オブジェクトの定義が含まれます。
第29 節では、SharedArrayBufferを利用したメモリへのアクセスの一貫性モデルおよびAtomicsオブジェクトのメソッドについて説明します。
5 記法上の規則
5.1 構文および字句文法
5.1.1 文脈自由文法
文脈自由文法 は複数の生成規則 から成ります。各生成規則は、非終端記号 と呼ばれる抽象記号を左辺 とし、0個以上の非終端記号および終端記号 記号から成る列を右辺 とします。各文法において、終端記号は特定のアルファベットから選ばれます。
連鎖生成規則 は、右辺にちょうど1つの非終端記号と0個以上の終端記号を持つ生成規則です。
特別な非終端記号(目標記号 )のみから成る文を始点として、与えられた文脈自由文法は言語 を規定します。つまり、非終端記号を対応する左辺を持つ生成規則の右辺へ繰り返し置換することで得られる終端記号の可能な(無限かもしれない)列の集合です。
5.1.2 字句文法と正規表現文法
ECMAScriptの字句文法 は、12 で示されています。この文法の終端記号は、SourceCharacter に定義された規則に従うUnicodeコードポイントです(11.1 参照)。この文法は、目標記号 であるInputElementDiv 、InputElementTemplateTail 、InputElementRegExp 、InputElementRegExpOrTemplateTail 、
またはInputElementHashbangOrRegExp から始まる生成規則群を定義し、これらがコードポイントの列を入力要素の列へと変換する方法を記述します。
空白やコメント以外の入力要素が、ECMAScriptの構文文法の終端記号となり、ECMAScriptのトークン と呼ばれます。これらのトークンは、予約語 、識別子、リテラル、およびECMAScript言語の区切り記号です。さらに、行終端子はトークンとはみなされませんが、入力要素の列に含まれ、自動セミコロン挿入 の処理を導きます。単純な空白や一行コメントは破棄され、構文文法の入力要素列には現れません。MultiLineComment (複数行にまたがるかどうかに関わらず/*…*/形式のコメント)は、行終端子を含まなければ単純に破棄されますが、行終端子を1つ以上含む場合は、1つの行終端子に置換され、構文文法の入力要素列に含まれます。
ECMAScriptの正規表現文法 は22.2.1 に示されます。この文法もSourceCharacter で定義されるコードポイントを終端記号とします。目標記号 であるPattern から始まる規則群を定義し、コードポイントの列を正規表現パターンへ変換する方法を記述します。
字句文法と正規表現文法の生成規則は、区切り記号として二重コロン“:: ”を用いて区別されます。字句文法と正規表現文法は、いくつかの生成規則を共有します。
5.1.3 数値文字列文法
数値文字列文法 は7.1.4.1 に現れます。終端記号はSourceCharacter であり、目標記号 であるStringNumericLiteral から(数値リテラルの字句文法 に似ているが異なる)、文字列を数値値へ変換するために使われます。
数値文字列文法の生成規則は、三重コロン“::: ”を区切り記号として区別され、ソーステキストの解析には決して使用されません。
5.1.4 構文文法
ECMAScriptの構文文法 は、13 から16 までの節で示されています。この文法の終端記号は、字句文法で定義されたECMAScriptトークンです(5.1.2 参照)。この文法は、目標記号 であるScript およびModule の2つの代替から始まる生成規則群を定義し、トークンの列がECMAScriptプログラムの構文的に正しい独立した構成要素を形成する方法を記述します。
コードポイントの列をECMAScriptのScript またはModule として解析する場合、まず字句文法を繰り返し適用して入力要素の列へ変換し、その後構文文法を1回適用して解析します。入力列のトークンが、目標非終端記号(Script またはModule )の単一インスタンスとして解析できず、余分なトークンが残る場合は、構文エラーとなります。
解析が成功すると、構文木 (根付き木構造)が構築されます。各ノードは構文ノード です。各構文ノードは文法記号のインスタンス であり、その記号から導出可能なソーステキストの範囲を表します。構文木の根ノード(ソーステキスト全体を表す)は、解析の目標記号 のインスタンスです。構文ノードが非終端記号のインスタンスである場合、その非終端記号を左辺に持つ生成規則のインスタンスでもあります。さらに、右辺の各記号に対応する子 を0個以上持ちます:各子は対応する記号のインスタンスである構文ノードです。
新しい構文ノードはパーサーの各呼び出しごとにインスタンス化され、同一ソーステキストであっても解析間で再利用されることはありません。構文ノードは、同じソーステキスト範囲を表し、同じ文法記号のインスタンスであり、同じパーサー呼び出しから生成された場合のみ同じ構文ノード とみなされます。
注1
同じ文字列を複数回解析すると、異なる構文ノードが得られます。例えば、次のようになります:
let str = "1 + 1;" ;
eval (str);
eval (str);
各evalの呼び出しは、strの値をECMAScriptソーステキスト へ変換し、個別に解析して独立した構文ノードの木を生成します。各構文木は、同じ文字列値から導出されたソーステキストであっても異なります。
注2
構文ノードは仕様上の概念であり、実装が同様のデータ構造を用いる必要はありません。
構文文法の生成規則は、区切り記号として単一コロン“: ”を用いて区別されます。
13 から16 までで示される構文文法は、ECMAScriptのScript またはModule として受理されるトークン列の完全な説明ではありません。特定の箇所(例えば行終端文字の前など)にセミコロンを追加した場合のみ記述されるトークン列など、追加で受理される場合があります。さらに、文法で記述されている一部のトークン列も、特定の“厄介な”位置に行終端文字がある場合は受理されません。
曖昧さを避けるために、構文文法では時折拡張生成規則を用いて、ECMAScriptのScript またはModule として有効ではないトークン列を許容する場合があります。例えば、この手法はオブジェクトリテラルやオブジェクト分割パターンで用いられます。その場合、より制限された補足文法 が提供され、受理されるトークン列を追加で制限します。通常、早期エラー 規則で、特定の文脈で「"P はN をカバーしなければならない 」と述べます。ここで、P は(拡張生成規則のインスタンスである)構文ノードであり、N は補足文法の非終端記号です。これは次を意味します:
P が元々マッチしたトークン列を、N を目標記号 として再度解析します。N が文法パラメータを持つ場合、P を元々解析したときと同じ値に設定します。
そのトークン列が、余分なトークンなく単一のN インスタンスとして解析できれば:
そのP に対して一意となるN のインスタンス(構文ノード)を「P がカバーするN 」と呼びます。
N および派生生成規則の全ての早期エラー規則は、P がカバーするN にも適用されます。
そうでなければ(解析に失敗した場合)、早期構文エラーとなります。
5.1.5 文法記法
5.1.5.1 終端記号
ECMAScriptの文法では、一部の終端記号が固定幅フォントで表示されています。これらはソーステキストに記載されたとおりに正確に現れる必要があります。この方法で指定されたすべての終端記号コードポイントは、他のUnicode範囲に類似したコードポイントではなく、Basic
Latinブロックの適切なUnicodeコードポイントとみなされます。終端記号内のコードポイントは、\ UnicodeEscapeSequence として表現することはできません。
終端記号が個々のUnicodeコードポイントである文法(すなわち字句文法、正規表現文法、数値文字列文法)では、生成規則に複数の固定幅コードポイントが連続して現れる場合、それは同じコードポイント列を個別の終端記号として記載する場合の省略記法です。
例えば、次の生成規則:
HexIntegerLiteral
::
0x
HexDigits
は次の省略記法です:
HexIntegerLiteral
::
0
x
HexDigits
対照的に、構文文法では固定幅コードポイントの連続は1つの終端記号となります。
終端記号には他にも2つの形式があります:
5.1.5.2 非終端記号と生成規則
非終端記号はイタリック体 で表示されます。非終端記号(「生成規則」とも呼ばれる)の定義は、定義される非終端記号の名前の後にコロンが1つ以上続いて導入されます(コロンの数は生成規則が属する文法を示します)。続く行に、その非終端記号の右辺の選択肢が1つ以上続きます。例えば、次の構文定義:
WhileStatement
:
while
(
Expression
)
Statement
は、非終端記号WhileStatement が、whileトークン、左括弧トークン、Expression 、右括弧トークン、Statement の順に現れることを表します。Expression やStatement も非終端記号です。別の例として、次の構文定義:
ArgumentList
:
AssignmentExpression
ArgumentList
,
AssignmentExpression
は、ArgumentList が、AssignmentExpression 単体、またはArgumentList の後にカンマ、その後AssignmentExpression が続く、いずれかを表すことを示します。このArgumentList の定義は再帰的であり、つまり自身を用いて定義されています。結果として、ArgumentList には任意の個数の引数(各引数式はAssignmentExpression )をカンマ区切りで含めることができます。このような再帰的定義は一般的です。
5.1.5.3 オプション記号
終端記号または非終端記号の後に付く下付き接尾辞「opt 」は、オプション記号を示します。オプション記号を含む選択肢は、オプション要素を省略する右辺と含める右辺の2つを実際に指定します。これはつまり:
VariableDeclaration
:
BindingIdentifier
Initializer opt
は次の省略記法です:
VariableDeclaration
:
BindingIdentifier
BindingIdentifier
Initializer
また:
ForStatement
:
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
は次の省略記法です:
ForStatement
:
for
(
LexicalDeclaration
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression
;
Expression opt
)
Statement
さらに次の省略記法となります:
ForStatement
:
for
(
LexicalDeclaration
;
)
Statement
for
(
LexicalDeclaration
;
Expression
)
Statement
for
(
LexicalDeclaration
Expression
;
)
Statement
for
(
LexicalDeclaration
Expression
;
Expression
)
Statement
したがって、この例では非終端記号ForStatement は実際には4つの右辺選択肢を持ちます。
5.1.5.4 文法パラメータ
生成規則は「[parameters] 」という下付き注釈でパラメータ化できます。これは、生成規則で定義される非終端記号の記号の後ろに接尾辞として現れます。「parameters 」は名前1つまたはカンマ区切りの名前リストです。パラメータ化された生成規則は、パラメータ名全組み合わせを定義する一連の生成規則の省略記法です。これはつまり:
StatementList [Return]
:
ReturnStatement
ExpressionStatement
は次の省略記法です:
StatementList
:
ReturnStatement
ExpressionStatement
StatementList_Return
:
ReturnStatement
ExpressionStatement
また:
StatementList [Return,
In] :
ReturnStatement
ExpressionStatement
は次の省略記法です:
StatementList
:
ReturnStatement
ExpressionStatement
StatementList_Return
:
ReturnStatement
ExpressionStatement
StatementList_In
:
ReturnStatement
ExpressionStatement
StatementList_Return_In
:
ReturnStatement
ExpressionStatement
複数パラメータの場合、生成規則の組み合わせ数は組み合わせ的に増えますが、すべてが完全な文法で参照されるとは限りません。
生成規則右辺で非終端記号への参照もパラメータ化できます。例えば:
StatementList
:
ReturnStatement
ExpressionStatement [+In]
は次の意味です:
StatementList
:
ReturnStatement
ExpressionStatement_In
また:
StatementList
:
ReturnStatement
ExpressionStatement [~In]
は次の意味です:
StatementList
:
ReturnStatement
ExpressionStatement
非終端記号参照はパラメータリストと「opt 」接尾辞の両方を持つことができます。例えば:
VariableDeclaration
:
BindingIdentifier
Initializer [+In] opt
は次の省略記法です:
VariableDeclaration
:
BindingIdentifier
BindingIdentifier
Initializer_In
右辺の非終端記号参照に「? 」を付けると、そのパラメータ値は現在の生成規則左辺記号の該当パラメータの有無によって決まります。例えば:
VariableDeclaration [In]
:
BindingIdentifier
Initializer [?In]
は次の省略記法です:
VariableDeclaration
:
BindingIdentifier
Initializer
VariableDeclaration_In
:
BindingIdentifier
Initializer_In
右辺選択肢が「[+parameter]」で始まる場合、その選択肢は指定したパラメータが該当生成規則非終端記号参照で使用されている場合のみ利用できます。「[~parameter]」で始まる場合は参照にそのパラメータが使われていない 場合のみ利用できます。これはつまり:
StatementList [Return]
: [+Return]
ReturnStatement
ExpressionStatement
は次の省略記法です:
StatementList
:
ExpressionStatement
StatementList_Return
:
ReturnStatement
ExpressionStatement
また:
StatementList [Return]
: [~Return]
ReturnStatement
ExpressionStatement
は次の省略記法です:
StatementList
:
ReturnStatement
ExpressionStatement
StatementList_Return
:
ExpressionStatement
5.1.5.5 one of
文法定義でコロンの後に「one of 」が続く場合、続く行に現れる各終端記号が選択肢となることを示します。例えば、ECMAScriptの字句文法には次の生成規則があります:
NonZeroDigit
:: one of 1
2 3 4 5 6
7 8 9
これは次の省略記法です:
NonZeroDigit
::
1
2
3
4
5
6
7
8
9
5.1.5.6 [empty]
生成規則の右辺に「[empty]」と記載されている場合、その生成規則の右辺には終端記号や非終端記号が含まれていないことを示します。
5.1.5.7 先読み制限
生成規則の右辺に「[lookahead =
seq ]」が現れる場合、その生成規則は直後の入力トークン列の先頭がseq である場合のみ使用可能であることを示します。同様に「[lookahead
∈ set ]」(set は有限 かつ空でないトークン列集合)は、その生成規則が直後のトークン列の先頭にset のいずれかが現れる場合のみ使用可能であることを示します。便宜上、集合は非終端記号で記載することもでき、その場合はその非終端記号が展開し得るすべてのトークン列集合を表します。非終端記号が無限に異なるトークン列に展開可能な場合は編集上の誤りとなります。
これらの条件は否定も可能です。「[lookahead ≠
seq ]」はseq が直後の入力トークン列の先頭ではない 場合のみ使用可能、「[lookahead ∉
set ]」はset のいずれも直後のトークン列先頭でない 場合のみ使用可能です。
例として、次の定義の場合:
DecimalDigit
:: one of 0
1 2 3 4 5
6 7 8 9
DecimalDigits
::
DecimalDigit
DecimalDigits
DecimalDigit
次の定義:
LookaheadExample
::
n
[lookahead ∉ { 1 , 3 , 5 ,
7 , 9 }]
DecimalDigits
DecimalDigit
[lookahead ∉ DecimalDigit ]
は、「n」の後に1つ以上の10進数字が続き、その先頭が偶数である場合、または10進数字がさらに続かない場合に一致します。
これらの表現が構文文法で使われる場合、直後のトークン列を一意に特定できない場合があります。これは、後続トークンを特定するには後の位置でどの字句目標記号 を使うか決める必要があるためです。そのため、構文文法でこれらを使う場合、先読み制限に現れるトークン列seq (集合の一部でも)が、字句目標記号 の選択によって先頭になるかどうかが変わる場合は編集上の誤りとなります。
構文文法の生成規則右辺に「[no LineTerminator
here]」と現れる場合、その生成規則は制限付き生成規則 であり、指定位置にLineTerminator が入力列に現れる場合は使用できません。例えば次の生成規則:
ThrowStatement
:
throw
[no LineTerminator here]
Expression
;
は、スクリプト内でthrowトークンとExpression の間にLineTerminator が現れる場合はこの生成規則が使えないことを示します。
制限付き生成規則でLineTerminator の存在が禁止されていない限り、入力要素列の任意の2つの連続トークンの間にはLineTerminator が何回現れても、スクリプトの構文的受理性には影響しません。
5.1.5.9 but not
生成規則右辺で「but not 」を使い、除外する展開を指定することができます。例えば次の生成規則:
Identifier
::
IdentifierName
but not ReservedWord
は、非終端記号Identifier が、IdentifierName で置換可能なコードポイント列のうち、同じコードポイント列がReservedWord で置換できないものだけを許容することを意味します。
5.1.5.10 説明的表現
最後に、選択肢をすべて列挙するのが非現実的な場合に限り、いくつかの非終端記号はサンセリフ体の説明的表現で記述されています:
SourceCharacter
::
任意のUnicodeコードポイント
5.2 アルゴリズム規約
この仕様書では、アルゴリズムの手順を指定するために番号付きリストを頻繁に使用します。これらのアルゴリズムは、ECMAScript言語構造の必要な意味論を正確に規定するために使われます。アルゴリズムは特定の実装技法の使用を示唆するものではありません。実際には、与えられた機能を実装するために、より効率的なアルゴリズムが利用可能な場合があります。
アルゴリズムは、順序付き・カンマ区切りの別名(エイリアス)名の列で明示的にパラメータ化される場合があります。これらはアルゴリズムの手順内で、その位置に渡された引数を参照するために使われます。オプションのパラメータは角括弧([
, name ])で囲んで表し、アルゴリズム手順内では必須のパラメータと同じ扱いになります。残余パラメータはパラメータリストの末尾に「...」を付けて(,
...name )表し、必須・オプションパラメータの後に渡されたすべての引数をList にまとめます。追加引数がなければ、そのList は空となります。
アルゴリズムの手順は、さらに順序付きのサブステップに分割できます。サブステップはインデントで示され、さらにインデントされたサブステップに分割できます。段階番号付け規則により、最初のレベルは英小文字、2番目はローマ小文字、3レベル以上は4番目以降で数字ラベルが使われます。例えば:
最上位の手順
サブステップ。
サブステップ。
サブサブステップ。
サブサブサブステップ
サブサブサブサブステップ
サブサブサブサブサブステップ
手順やサブステップは「if」条件文として記述でき、その場合サブステップは条件が真の時のみ適用されます。同じレベルの「if」条件文の次に「else」で始まる手順やサブステップは、その条件の否定です。
手順では、サブステップの反復適用を指定することもできます。
「Assert :」で始まる手順は、そのアルゴリズムの不変条件を主張します。これらの主張は、暗黙的なアルゴリズムの不変条件を明示するためのものであり、追加の意味論的要件を加えるものではなく、実装で検証する必要はありません。単にアルゴリズムの明確化のために用いられます。
アルゴリズムの手順では「Let x be
someValue 」の形式で値に名前付きエイリアスを宣言できます。これらのエイリアスは参照的であり、x とsomeValue は同じデータを参照し、どちらかの変更は双方に反映されます。参照的動作を避けたい場合は、手順内で「Let
x be a copy of someValue 」のように右辺のコピーを明示的に作成する必要があります。
宣言されたエイリアスは、その後の手順で参照できますが、宣言前の手順で参照してはなりません。エイリアスは「Set x to
someOtherValue 」の形式で変更できます。
5.2.1 抽象操作
この仕様の複数箇所で使用できるように、いくつかのアルゴリズムは抽象操作 と呼ばれ、パラメータ化された関数形式で名前付き定義され、他のアルゴリズムから名前で参照できるようになっています。抽象操作は通常、OperationName(arg1 ,
arg2 )のような関数適用形式で参照されます。一部の抽象操作は、クラス的な仕様抽象の多態的にディスパッチされるメソッドとして扱われます。そのようなメソッド的抽象操作は、someValue .OperationName(arg1 ,
arg2 )のように参照されます。
5.2.2 構文指向操作
構文指向操作 は、名前付き操作であり、その定義はECMAScript文法の生成規則(複数の選択肢がある場合はそれぞれ)に関連付けられたアルゴリズムから成ります。複数の選択肢がある生成規則には通常、各選択肢ごとに別個のアルゴリズムがあります。アルゴリズムが文法生成規則に関連付けられる場合、生成規則の終端記号および非終端記号は、アルゴリズムのパラメータのように参照できます。この際、非終端記号は、ソーステキストを解析した際に一致した実際の選択肢定義を参照します。文法生成規則やそれから派生したParse
Node によって一致した source text matched
by は、一致に参加した最初の終端記号の開始位置から最後の終端記号の終了位置までのソーステキストの範囲です。
生成規則選択肢に関連付けられたアルゴリズムは、通常「[ ]」などの文法注釈なしで示されます。これらの注釈は構文的認識にのみ影響し、選択肢の意味論には影響しません。
構文指向操作は、構文ノードおよび必要に応じて他のパラメータを受けて、以下のアルゴリズムの1 、3 、4 の手順に従って呼び出します:
Let status be SyntaxDirectedOperation of
SomeNonTerminal .
Let someParseNode be the parse of some source text.
Perform SyntaxDirectedOperation of
someParseNode .
Perform SyntaxDirectedOperation of
someParseNode with argument "value" .
明示的に指定されない限り、すべての連鎖生成規則 には、その左辺非終端記号に適用される可能性のあるすべての操作の暗黙的定義があります。暗黙定義は、同じ操作・同じパラメータ(もしあれば)を唯一の右辺非終端記号に再適用し結果を返します。例えば、あるアルゴリズムが「Return
Evaluation
of Block 」という手順を持ち、次のような生成規則があるとします:
Block :
{
StatementList
}
しかし、Evaluation 操作がその生成規則にアルゴリズムを関連付けていない場合は、Evaluation 操作には次のような関連付けが暗黙的に含まれます:
実行時意味論: Evaluation
Block :
{
StatementList
}
Return Evaluation of StatementList .
5.2.3 実行時意味論
実行時に呼び出される必要のある意味論を規定するアルゴリズムは実行時意味論 と呼ばれます。実行時意味論は抽象操作 または構文指向操作 で定義されます。
5.2.3.1 Completion ( completionRecord )
抽象操作Completionは、引数completionRecord (Completion
Record )を受け取り、Completion
Record を返します。これはCompletion
Record が返されることを強調するために使われます。呼び出し時、次の手順を実行します:
Assert :
completionRecord はCompletion
Record である。
completionRecord を返す。
5.2.3.2 例外を投げる
「例外を投げる」と記載されたアルゴリズム手順(例):
TypeError例外を投げる。
は次の記述と同じ意味です:
新しく作成したTypeErrorオブジェクトでThrowCompletion を返す。
5.2.3.3 ReturnIfAbrupt
「ReturnIfAbrupt (argument )」と記載された、またはそれと同等の意味を持つアルゴリズム手順:
ReturnIfAbrupt (argument )。
は次の意味です:
Assert :
argument はCompletion
Record である。
もしargument がabrupt
completion なら、Completion (argument )を返す。
それ以外は、argument をargument .[[Value]] に設定する。
また、「ReturnIfAbrupt (AbstractOperation())」と記載された場合:
Let hygienicTemp be AbstractOperation()。
Assert :
hygienicTemp はCompletion
Record である。
もしhygienicTemp がabrupt
completion なら、Completion (hygienicTemp )を返す。
それ以外は、hygienicTemp をhygienicTemp .[[Value]] に設定する。
ここでhygienicTemp はReturnIfAbruptに関する手順内のみ一時的に有効です。
また、「Let result be AbstractOperation(ReturnIfAbrupt (argument ))」と記載された場合:
Assert :
argument はCompletion
Record である。
もしargument がabrupt
completion なら、Completion (argument )を返す。
それ以外は、argument をargument .[[Value]] に設定する。
Let result be AbstractOperation(argument )。
5.2.3.4 ReturnIfAbruptの省略記法
抽象操作 および構文指向操作 の呼び出し前に?を付けることで、結果のCompletion
Record に対してReturnIfAbrupt を適用することを示します。例えば:
? OperationName()。
は次の手順と同じ意味です:
ReturnIfAbrupt (OperationName())。
同様に、メソッド呼び出し形式の場合:
? someValue .OperationName()。
は次の意味です:
ReturnIfAbrupt (someValue .OperationName())。
また、!を前置することで、抽象操作や構文指向操作 の呼び出しが決してabrupt
completion を返さないことを示し、結果のCompletion
Record の[[Value]] フィールドのみを返り値として使用します。例えば:
Let val be ! OperationName()。
は次の手順と同じ意味です:
Let val be OperationName()。
Assert :
val はnormal
completion である。
val をval .[[Value]] に設定する。
構文指向操作 による実行時意味論 では、この省略記法を使い、操作呼び出し前に!または?を付けます:
Perform ! SyntaxDirectedOperation of NonTerminal 。
5.2.3.5 暗黙的な通常完了
抽象操作 のアルゴリズム内で、返り値がCompletion
Record として宣言されている場合や、すべての組み込み関数内では、返される値は最初にNormalCompletion に渡され、その結果が使用されます。この規則はCompletion アルゴリズム内や、返す値がその手順で明示的にCompletion
Record であることを明示している場合には適用されません。これらのケースは:
それ以外の方法でCompletion
Record を返すと編集上の誤りとなります。例えば、これらの抽象操作 内で、
Return true 。
は次のいずれとも同じ意味です:
Return NormalCompletion (true )。
または
Let completion be NormalCompletion (true )。
Return Completion (completion )。
または
Return Completion
Record { [[Type]] :
normal , [[Value]] :
true , [[Target]] :
empty }。
ReturnIfAbrupt の展開では、展開手順内でCompletion の結果が直接返される場合は許容され、通常ケースではアンラップ後に暗黙的NormalCompletion が適用されます。
Return ? completion 。
次の例は編集上の誤りです。なぜならCompletion
Record がその手順で注釈なしに返されているからです。
Let completion be NormalCompletion (true )。
Return completion 。
5.2.4 静的意味論
文脈自由文法だけでは、入力要素列が評価可能な有効なECMAScriptScript またはModule かどうかを定めるすべての規則を表現できません。場合によっては、ECMAScriptアルゴリズム規約か記述的要件で表現される追加規則が必要です。これらの規則は常に文法の生成規則に関連付けられ、該当生成規則の静的意味論 と呼ばれます。
静的意味論規則は名前を持ち、通常アルゴリズムで定義されます。名前付き静的意味論規則は文法生成規則に関連付けられ、複数の選択肢がある生成規則には通常、各選択肢ごと・各適用規則ごとに別個のアルゴリズムが定義されます。
静的意味論規則の特例として早期エラー規則 があります。早期エラー 規則は、特定文法生成規則に関連付けられた早期エラー 条件(17 参照)を定義します。ほとんどのEvaluation は、仕様書のアルゴリズム内で早期エラー規則を明示的に呼び出しません。適合実装は、Script またはModule の最初の評価前に、パースに使われた生成規則のすべての早期エラー 規則を検証する必要があります。もし早期エラー 規則が違反された場合、そのScript またはModule は無効となり評価できません。
5.2.5 数学演算
この仕様書では、次の種類の数値値を参照します:
この仕様書では、数値値の種類を下付き接尾辞で区別します。下付き𝔽 はNumbersを、下付きℤ はBigIntsを指します。下付き接尾辞のない数値値は数学値 を指します。ほとんどの数値値は10進法で記載されますが、0xに続く数字0-9やA-Fの形式で16進法値も使われます。
この仕様書で数値値について言及する場合(例:「y の長さ」や「4つの16進数字で表される整数 」など)、数値種別が明示されていなければ、数学値 を指します。Number値やBigInt値に言及する場合は明示的に注釈されます(例:「…のNumber値」、「…のBigInt値」など)。
この仕様書で 整数 という用語が使われる場合、特に断りがなければ、数学値 で、整数 の集合に属するものを指します。 整数型Number という用語は、有限 なNumber値で、その数学値が整数 の集合に含まれるものを指します。
+, ×, =, ≥などの数値演算子は、オペランドの型ごとに対応する演算を指します。数学値 に適用される場合は通常の数学演算、拡張数学値 では拡張実数上の通常の数学演算(不定形は未定義で仕様書の編集上誤り)、NumbersではIEEE
754-2019 の該当演算、BigIntsではBigIntの数学値に対する通常の数学演算が適用されます。型混合(例:Numberと数学値)の演算子は未定義で仕様書の編集上誤りです。
数学値 とNumbersやBigInts間の変換は常に明示的です。数学値 や拡張数学値 x からNumberへの変換は「the
Number value
for x 」または𝔽(x ) で表し、6.1.6.1 で定義されます。整数 x からBigIntへの変換は「the BigInt value for x 」またはℤ(x ) で表します。NumberやBigIntx から数学値への変換は「the mathematical value of
x 」またはℝ(x ) です。数学値 +0 𝔽 や-0 𝔽 は数学値0です。非有限 値の数学値は未定義です。拡張数学値 x は、有限値ならその数学値、+∞ 𝔽 なら+∞、-∞ 𝔽 なら-∞、NaN には未定義です。
数学関数abs(x ) はx の絶対値(x <
0なら-x 、それ以外はx 自身)を返します。
数学関数min(x1 , x2 , … ,
xN ) はx1からxNまでの最小値を返し、max(x1 , x2 , ...,
xN ) は最大値を返します。これらの関数の定義域と値域は拡張数学値 です。
記法「x modulo
y 」(y は有限 かつ非ゼロ)は、y と同符号(またはゼロ)の値k を計算し、abs (k ) < abs (y ) かつx -
k = q × y (q は整数 )となる値です。
「clamping x between lower and
upper 」とは、xがlower 未満ならlower 、upper より大きければupper 、それ以外はx自身を返します(lower とupper は数学値でlower
≤ upper )。
数学関数floor(x ) は、x以下で最大(+∞に最も近い)整数 を返します。
注
floor (x ) = x -
(x modulo 1) です。
数学関数truncate(x ) は、小数部を切り捨ててゼロ方向に丸めます。x < 0なら-floor (-x )、それ以外はfloor (x )を返します。
数学関数min 、max 、abs 、floor 、truncate はNumbersやBigIntsには定義されていません。非数学値 引数でこれらを使うと仕様書の編集上誤りです。
区間 は、下限a から上限b までの、同じ数値型の値の集合(無限・空の場合もありえます)です。各境界は包含か非包含かが示されます。区間には次の4種があります:
下限a(含む)から上限b(含む)の区間(包含区間 )は、a ≤ x ≤
bを満たすすべてのxのみ含みます。
下限a(含む)から上限b(含まない)の区間は、a ≤ x < bを満たすxのみ含みます。
下限a(含まない)から上限b(含む)の区間は、a < x ≤ bを満たすxのみ含みます。
下限a(含まない)から上限b(含まない)の区間は、a < x < bを満たすxのみ含みます。
例えば、下限1(含む)から上限2(含まない)の区間は、1以上2未満のすべての数学値 (1を含み2を含まない)からなります。区間定義では、-0 𝔽
<
+0 𝔽 (比較対0の記述回避のためコメントあり)、したがって下限+0 𝔽 の包含区間は+0 𝔽 のみ含み-0 𝔽 は含みません。NaN は区間に含まれません。
5.2.6 値記法
この仕様書では、ECMAScript言語値 は太字 で表示されます。例えばnull 、true 、"hello" などです。これらはECMAScriptソーステキスト (例:Function.prototype.applyやlet n = 42;)とは区別されます。
5.2.7 同一性
この仕様書では、仕様値とECMAScript言語値 は等価性比較されます。値の比較には2種類があります。同一性のない値 は、すべての固有特性(整数の大きさや配列の長さなど)が一致すれば他の同一性のない値と等しいとみなされます。同一性のない値は、特性を完全に記述するだけで現すことができます。対して、同一性を持つ値 は一意であり、自分自身としか等価でありません。同一性を持つ値は、同一性のない値の性質に加え、推測不可・変更不可・世界的に一意な特性「同一性」を持ちます。既存の同一性を持つ値への参照は、その特性を記述するだけでは現せず、明示的に値の参照を受け渡す必要があります。いくつかの同一性を持つ値は可変であり、特性(同一性以外)がインプレースで変更され、値を保持するすべての場所で新しい特性が観測されます。同一性のない値は同一性を持つ値と等価になることはありません。
この仕様書の観点では、「is」は2つの値の等価性比較(例:「If bool is true , then
...」)、「contains」はリスト内で値を等価性比較して探索(例:「If list contains a Record r such
that r .[[Foo]] is true , then
...」)に使われます。仕様上の同一性はこれらの比較結果を決定し、仕様書内で公理的です。
ECMAScript言語の観点では、言語値はSameValue 抽象操作およびそれが間接的に呼び出す抽象操作 で等価性比較されます。これらの比較抽象操作 のアルゴリズムが、ECMAScript言語値 の言語上の同一性を決定します。
仕様値の例として、同一性のない値には、数学値 、拡張数学値 、ECMAScriptソーステキスト 、サロゲートペア 、Directive
Prologues など、UTF-16コードユニット、Unicodeコードポイント、列挙型 、抽象操作 (構文指向操作 やホストフック など含む)、順序対など。同一性を持つ仕様値の例には、Record (Property
Descriptor やPrivateElements など含む)、構文ノード 、List 、Set やRelation 、Abstract
Closure 、Data Block 、Private Name 、実行コンテキスト や実行コンテキストスタック 、エージェント識別子 、WaiterList
Record など。
仕様上の同一性は、Symbol値(Symbol.for で生成されたものを除く)を除き、すべてのECMAScript言語値 について言語上の同一性と一致します。仕様・言語同一性を持たないECMAScript言語値 は、undefined 、null 、Boolean 、String 、Number 、BigInt です。仕様・言語同一性を持つ値は、Symbol値(Symbol.for で生成されないもの)とObject です。Symbol.for で生成されたSymbol値は仕様上の同一性は持ちますが言語上の同一性は持ちません。
6 ECMAScriptのデータ型と値
この仕様のアルゴリズムは、型が関連付けられた値を操作します。値の型は、まさにこの節で定義されているものだけです。型はさらにECMAScript言語型 と仕様型に分類されます。
6.1 ECMAScript言語型
ECMAScript言語型 は、ECMAScriptプログラマがECMAScript言語で直接操作する値に対応します。ECMAScript言語型は、Undefined、Null、Boolean、String、Symbol、Number、BigInt、Objectです。ECMAScript言語値 は、ECMAScript言語型で特徴付けられる値です。
6.1.1 Undefined型
Undefined型は、undefined と呼ばれるただ1つの値だけを持ちます。値が代入されていない変数は、undefined の値を持ちます。
6.1.2 Null型
Null型は、null と呼ばれるただ1つの値だけを持ちます。
6.1.3 Boolean型
Boolean型 は、true とfalse という2つの値を持つ論理的な実体を表します。
6.1.4 String型
String型 は、最大長253 -1要素までの、0個以上の16ビット符号なし整数 値(「要素」)の順序付き列の集合です。String型は主に、実行中のECMAScriptプログラムでテキストデータを表すために利用されます。この場合、String内の各要素はUTF-16コード単位値として扱われます。各要素は列内の位置に存在し、位置は非負の整数 でインデックスされます。最初の要素(あれば)はインデックス0、次の要素(あれば)はインデックス1、と続きます。Stringの長さはその中の要素(16ビット値)の数です。空文字列は長さ0で、要素を持ちません。
String内容を解釈しないECMAScript操作は、これ以上意味論を与えません。String値を解釈する操作は、各要素を単一のUTF-16コード単位として扱います。ただし、ECMAScriptはこれらのコード単位の値や関係性を制限しないため、さらにString内容をUTF-16で符号化されたUnicodeコードポイントの列として解釈する操作は、不正な部分列を考慮する必要があります。こうした操作は、数値値が0xD800から0xDBFFの包含区間 (Unicode標準ではリーディングサロゲート 、または正式にはハイサロゲートコード単位 )であるすべてのコード単位、また数値値が0xDC00から0xDFFFの包含区間 (トレーリングサロゲート 、または正式にはローサロゲートコード単位 )であるすべてのコード単位に特別な処理を以下の規則で適用します:
関数String.prototype.normalize(22.1.3.15 )はString値を明示的に正規化できます。String.prototype.localeCompare(22.1.3.12 )は内部でString値を正規化しますが、他の操作は文字列を暗黙的に正規化しません。操作結果は特に記載がなければ言語・ロケールに依存しません。
注
この設計の理由は、Stringの実装を可能な限り単純かつ高性能に保つことにありました。ECMAScriptソーステキスト が正規化形式Cであれば、文字列リテラルはUnicodeエスケープシーケンスを含まない限り、正規化されていることが保証されます。
この仕様では、「string-concatenation of A ,
B , ...」という表現(各引数はString値、コード単位、またはコード単位の列)は、それぞれの引数(順番通り)のコード単位列を連結したString値を指します。
「substring of S from inclusiveStart
to
exclusiveEnd 」という表現(S はString値またはコード単位の列、inclusiveStart とexclusiveEnd は整数 )は、S のインデックスinclusiveStart からexclusiveEnd 直前までの連続コード単位のString値を指します(inclusiveStart
= exclusiveEnd の場合は空文字列)。「to」省略時は、S の長さがexclusiveEnd となります。
この仕様の「ASCIIワード文字 」は、Unicode Basic
Latinブロックのすべての文字と数字、およびU+005F(LOW LINE)だけからなる次のString値を指します:
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" 。
歴史的理由により、いくつかのアルゴリズムで重要な意味を持ちます。
6.1.4.1 StringIndexOf ( string ,
searchValue , fromIndex )
抽象操作StringIndexOfは、引数string (String)、searchValue (String)、fromIndex (非負の整数 )を取り、非負の整数 またはnot-found を返します。呼び出し時、次の手順を実行します:
len をstring の長さとする。
searchValue が空文字列かつfromIndex ≤
len なら、fromIndex を返す。
searchLen をsearchValue の長さとする。
fromIndex ≤ i ≤ len -
searchLen となるすべての整数 i について昇順で:
candidate をstring のi からi +
searchLen までのsubstring とする。
candidate がsearchValue と等しければ、i を返す。
not-found を返す。
注1
searchValue が空文字列かつfromIndex ≤
string の長さなら、このアルゴリズムはfromIndex を返します。空文字列は文字列内のすべての位置(最後のコード単位の後も含む)で見つかったものとみなされます。
注2
fromIndex +
searchValue の長さがstring の長さを超える場合、このアルゴリズムは常にnot-found を返します。
6.1.4.2 StringLastIndexOf ( string ,
searchValue , fromIndex )
抽象操作StringLastIndexOfは、引数string (String)、searchValue (String)、fromIndex (非負の整数 )を取り、非負の整数 またはnot-found を返します。呼び出し時、次の手順を実行します:
len をstring の長さとする。
searchLen をsearchValue の長さとする。
Assert :
fromIndex + searchLen ≤ len 。
0 ≤ i ≤ fromIndex となるすべての整数 i について降順で:
candidate をstring のi からi +
searchLen までのsubstring とする。
candidate がsearchValue と等しければ、i を返す。
not-found を返す。
注
searchValue が空文字列の場合、このアルゴリズムはfromIndex を返します。空文字列は文字列内のすべての位置(最後のコード単位の後も含む)で見つかったものとみなされます。
6.1.5 Symbol型
Symbol型 は、Objectプロパティのキーとして使用できるすべての非String値の集合です(6.1.7 参照)。
Symbol値はそれぞれ一意かつ不変です。
各Symbol値は、undefined またはString値である[[Description]] という関連値を不変に保持します。
6.1.5.1 既知のSymbol
既知のSymbolは、この仕様のアルゴリズムで明示的に参照される組み込みのSymbol値です。これらは通常、仕様アルゴリズムの拡張ポイントとなる値を持つプロパティのキーとして使用されます。特に規定がなければ、既知のSymbol値はすべてのrealm (9.3 参照)で共有されます。
この仕様書では、既知のSymbolは標準のintrinsic記法 で参照されます。intrinsicは表1 に記載されている値のいずれかです。
注
以前の仕様書の版では@@name形式の記法が使われていましたが、現行版では%Symbol.name%が使われます。特に次の名前が使われていました:@@asyncIterator、@@hasInstance、@@isConcatSpreadable、@@iterator 、@@match、@@matchAll、@@replace、@@search、@@species、@@split、@@toPrimitive、@@toStringTag、および@@unscopables。
表1: 既知のSymbol
仕様名
[[Description]]
値と目的
%Symbol.asyncIterator%
"Symbol.asyncIterator"
オブジェクトのデフォルトの非同期イテレータ を返すメソッド。for-await-of文の意味論で呼び出されます。
%Symbol.hasInstance%
"Symbol.hasInstance"
constructor オブジェクトが、オブジェクトを自身のインスタンスとして認識するかを判定するメソッド。instanceof演算子の意味論で呼び出されます。
%Symbol.isConcatSpreadable%
"Symbol.isConcatSpreadable"
この値がtrueなら、Array.prototype.concat でオブジェクトが配列要素としてフラット化されることを示すBoolean値プロパティ。
%Symbol.iterator%
"Symbol.iterator"
オブジェクトのデフォルトのイテレータ を返すメソッド。for-of文の意味論で呼び出されます。
%Symbol.match%
"Symbol.match"
正規表現メソッドで、正規表現を文字列に対してマッチさせます。String.prototype.match メソッドで呼び出されます。
%Symbol.matchAll%
"Symbol.matchAll"
正規表現メソッドで、文字列に対してマッチした結果を返すイテレータ を返します。String.prototype.matchAll メソッドで呼び出されます。
%Symbol.replace%
"Symbol.replace"
正規表現メソッドで、文字列の一致部分を置換します。String.prototype.replace メソッドで呼び出されます。
%Symbol.search%
"Symbol.search"
正規表現メソッドで、文字列内で正規表現に一致するインデックスを返します。String.prototype.search メソッドで呼び出されます。
%Symbol.species%
"Symbol.species"
派生オブジェクトの生成に使われるconstructor 関数値プロパティ。
%Symbol.split%
"Symbol.split"
正規表現メソッドで、正規表現に一致するインデックスで文字列を分割します。String.prototype.split メソッドで呼び出されます。
%Symbol.toPrimitive%
"Symbol.toPrimitive"
オブジェクトを対応するプリミティブ値に変換するメソッド。ToPrimitive 抽象操作で呼び出されます。
%Symbol.toStringTag%
"Symbol.toStringTag"
オブジェクトのデフォルト文字列記述の生成に使われるString値プロパティ。組み込みObject.prototype.toString メソッドでアクセスされます。
%Symbol.unscopables%
"Symbol.unscopables"
オブジェクト値プロパティで、自身と継承したプロパティ名が、関連オブジェクトのwith環境バインディングから除外されるプロパティ名となります。
6.1.6 数値型
ECMAScriptには2つの組み込み数値型、Number型とBigInt型があります。以下の抽象操作 がこれらの数値型に対して定義されています。「Result」列は戻り値の型と、ある呼び出しでabrupt
completion が返される可能性があるかどうかを示します。
表2: 数値型演算
操作
例(ソース)
評価 意味論で呼び出される...
結果
Number::unaryMinus
-x
単項-演算子
Number
BigInt::unaryMinus
BigInt
Number::bitwiseNOT
~x
ビット単位NOT演算子(~)
Number
BigInt::bitwiseNOT
BigInt
Number::exponentiate
x ** y
べき乗演算子
および Math.pow ( base , exponent
)
Number
BigInt::exponentiate
正常完了(BigIntを含む) またはthrow
completion
Number::multiply
x * y
乗算演算子
Number
BigInt::multiply
BigInt
Number::divide
x / y
乗算演算子
Number
BigInt::divide
正常完了(BigIntを含む) またはthrow
completion
Number::remainder
x % y
乗算演算子
Number
BigInt::remainder
正常完了(BigIntを含む) またはthrow
completion
Number::add
x ++
++ x
x + y
後置インクリメント演算子 ,
前置インクリメント演算子 ,
および加算演算子(+)
Number
BigInt::add
BigInt
Number::subtract
x --
-- x
x - y
後置デクリメント演算子 ,
前置デクリメント演算子 ,
および減算演算子(-)
Number
BigInt::subtract
BigInt
Number::leftShift
x << y
左シフト演算子(<<)
Number
BigInt::leftShift
BigInt
Number::signedRightShift
x >> y
符号付き右シフト演算子(>>)
Number
BigInt::signedRightShift
BigInt
Number::unsignedRightShift
x >>> y
符号なし右シフト演算子(>>>)
Number
BigInt::unsignedRightShift
throw
completion
Number::lessThan
x < y
x > y
x <= y
x >= y
比較演算子 ,
IsLessThan ( x , y ,
LeftFirst ) 経由
Boolean または undefined (比較不能な入力の場合)
BigInt::lessThan
Boolean
Number::equal
x == y
x != y
x === y
x !== y
等価演算子 ,
IsStrictlyEqual ( x ,
y ) 経由
Boolean
BigInt::equal
Number::sameValue
Object.is(x, y)
オブジェクト内部メソッド,
SameValue ( x , y
) 経由,
厳密な値の等価性テスト用
Boolean
Number::sameValueZero
[x].includes(y)
SameValueZero ( x , y
) 経由,
Array, Map,
Setメソッドで+0 𝔽 と-0 𝔽 の違いを無視して値の等価性テスト
Boolean
Number::bitwiseAND
x & y
ビット単位バイナリ演算子
Number
BigInt::bitwiseAND
BigInt
Number::bitwiseXOR
x ^ y
Number
BigInt::bitwiseXOR
BigInt
Number::bitwiseOR
x | y
Number
BigInt::bitwiseOR
BigInt
Number::toString
String(x)
多くの式や組み込み関数、ToString (
argument ) 経由
String
BigInt::toString
数値型は一般に精度損失や切り捨てなしには変換できないため、ECMAScript言語ではこれらの型間で暗黙的な変換を提供しません。型が異なる関数を呼び出す場合、プログラマはNumberやBigInt関数を使って明示的に変換する必要があります。
注
ECMAScriptの初版および後続版では、特定の演算子に対し、精度損失や切り捨て が生じる暗黙的数値変換が提供されていました。これらのレガシーな暗黙変換は後方互換性のために維持されていますが、BigIntではプログラマの誤りの機会を最小化し、将来版で汎用的な値型 を導入する余地を残すために提供されていません。
6.1.6.1 Number型
Number型 は、18,437,736,874,454,810,627(すなわち264 - 253 + 3 )個の値を持ち、IEEE Standard for
Binary Floating-Point Arithmeticで規定される倍精度浮動小数点IEEE
754-2019 binary64値を表します。ただし、IEEE標準の9,007,199,254,740,990(すなわち253 -
2 )個の異なるNaN値は、ECMAScriptでは単一の特別なNaN 値として表現されます。(NaN はプログラム式NaNで生成されます。)一部の実装では外部コードにより異なるNaN値を検出できる場合もありますが、その挙動は実装定義 です。ECMAScriptコードからはすべてのNaN 値は区別できません。
注
Number値をArrayBuffer(25.1 )やSharedArrayBuffer(25.2 )に格納した後に観測されるビットパターンは、ECMAScript実装で使用されるそのNumber値の内部表現と必ずしも一致しません。
他にも正の無限大 (+∞ 𝔽 )と負の無限大 (-∞ 𝔽 )という特別な値があります。(これら2つの無限のNumber値は、プログラム式+Infinity(または単にInfinity)、-Infinityで生成されます。)
その他18,437,736,874,454,810,624(264 -
253 )個の値は有限数 と呼ばれます。半数が正、半数が負であり、各有限 な正のNumber値ごとに同じ大きさの負の値があります。
正のゼロ と負のゼロ の両方が存在します。(これら2つのゼロ値は、プログラム式+0(または単に0)、-0で生成されます。)
18,437,736,874,454,810,622(264 -
253 - 2 )個の有限 非ゼロ値は2種類あります:
18,428,729,675,200,069,632(264 -
254 )個は正規化され、次の形を持ちます:
s × m × 2e
ここでs は1または-1、m は整数 で、区間 252 (含む)~253 (含まない)、e は整数 で、-1074から971の包含区間 です。
残りの9,007,199,254,740,990(253 -
2 )個の値は非正規化され、次の形を持ちます:
s × m × 2e
ここでs は1または-1、m は整数 で、区間 0(含まない)~252 (含まない)、e は-1074です。
大きさが253 以下のすべての正負の整数 はNumber型で表現可能です。整数0は、Number型において+0 𝔽 と-0 𝔽 の2種類の表現があります。
有限 数値が非ゼロであり、上記の形で表現される整数 m が奇数なら「奇数有効桁」、そうでなければ「偶数有効桁」を持ちます。
この仕様の「the Number value for
x 」という表現(x は正確な実数数学量、πなどの無理数であってもよい)は、次の手順で選ばれたNumber値を意味します。Number型のすべての有限 値から-0 𝔽 を除き、さらに型で表現できない値21024 (+1 × 253 × 2971 )および-21024 (-1 ×
253 ×
2971 )を加えた集合を考えます。この集合の中でx に最も近い値を選びます。2つの値が同じ距離なら偶数有効桁の方を選びます(2つの追加値も偶数有効桁とみなす)。最終的に21024 が選ばれたら+∞ 𝔽 に、-21024 が選ばれたら-∞ 𝔽 に、+0 𝔽 が選ばれたらx
< 0のときのみ-0 𝔽 に、それ以外は選ばれた値をそのまま使います。この結果がNumber value
for x です。(この手順はIEEE
754-2019 のroundTiesToEvenモードと正確に一致します。)
Number
value for +∞は+∞ 𝔽 、Number value
for -∞は-∞ 𝔽 です。
一部のECMAScript演算子は、特定範囲の整数 のみ扱います(例:-231 から231 -1の包含区間 や0から216 -1の包含区間 )。これらの演算子はNumber型の任意の値を受け付け、まず期待範囲の整数 値に変換します。数値変換操作の詳細は7.1 を参照してください。
6.1.6.1.1 Number::unaryMinus ( x )
抽象操作Number::unaryMinusは、引数x (Number型)を受け取り、Number型を返します。呼び出し時、次の手順を実行します:
x がNaN なら、NaN を返す。
x の符号を反転したNumber値(絶対値は同じで符号が逆)を返す。
6.1.6.1.2 Number::bitwiseNOT ( x )
抽象操作Number::bitwiseNOTは、引数x (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
oldValue を! ToInt32 (x )とする。
oldValue のビット反転を返す。結果の数学値 は32ビットの2の補数ビット列として正確に表現可能。
6.1.6.1.3 Number::exponentiate ( base ,
exponent )
抽象操作Number::exponentiateは、引数base (Number型)とexponent (Number型)を受け取り、Number型を返します。base のexponent 乗の結果を表す実装近似値 を返します。呼び出し時、次の手順を実行します:
exponent がNaN ならNaN を返す。
exponent が+0 𝔽 または-0 𝔽 なら、1 𝔽 を返す。
base がNaN ならNaN を返す。
base が+∞ 𝔽 なら、
exponent >
+0 𝔽 なら+∞ 𝔽 を、そうでなければ+0 𝔽 を返す。
base が-∞ 𝔽 なら、
exponent > +0 𝔽 なら
exponent が奇数整数型Number なら-∞ 𝔽 を、そうでなければ+∞ 𝔽 を返す。
それ以外の場合
exponent が奇数整数型Number なら-0 𝔽 を、そうでなければ+0 𝔽 を返す。
base が+0 𝔽 なら、
exponent >
+0 𝔽 なら+0 𝔽 を、そうでなければ+∞ 𝔽 を返す。
base が-0 𝔽 なら、
exponent > +0 𝔽 なら
exponent が奇数整数型Number なら-0 𝔽 を、そうでなければ+0 𝔽 を返す。
それ以外の場合
exponent が奇数整数型Number なら-∞ 𝔽 を、そうでなければ+∞ 𝔽 を返す。
Assert :
base は有限 で、+0 𝔽 でも-0 𝔽 でもない。
exponent が+∞ 𝔽 なら、
abs (ℝ (base )) >
1なら+∞ 𝔽 を返す。
abs (ℝ (base )) =
1ならNaN を返す。
abs (ℝ (base )) <
1なら+0 𝔽 を返す。
exponent が-∞ 𝔽 なら、
abs (ℝ (base )) >
1なら+0 𝔽 を返す。
abs (ℝ (base )) =
1ならNaN を返す。
abs (ℝ (base )) <
1なら+∞ 𝔽 を返す。
Assert :
exponent は有限 で、+0 𝔽 でも-0 𝔽 でもない。
base <
-0 𝔽 かつexponent が整数型Number でなければ、NaN を返す。
実装近似値 のNumber値(ℝ (base )のℝ (exponent )乗)を返す。
注
base が1 𝔽 または-1 𝔽 で、exponent が+∞ 𝔽 または-∞ 𝔽 の場合、またはbase が1 𝔽 でexponent がNaN の場合のbase
** exponent の結果は、IEEE
754-2019 と異なります。ECMAScript初版ではこの演算の結果をNaN と規定していましたが、後のIEEE
754では1 𝔽 となっています。互換性維持のため、ECMAScriptの従来の挙動を残しています。
6.1.6.1.4 Number::multiply ( x , y )
抽象操作Number::multiplyは、引数x (Number型)、y (Number型)を受け取り、Number型を返します。IEEE
754-2019 の倍精度浮動小数点演算規則に従い、x とy の積を計算します。呼び出し時、次の手順を実行します:
x がNaN またはy がNaN なら、NaN を返す。
x が+∞ 𝔽 または-∞ 𝔽 なら、
y が+0 𝔽 または-0 𝔽 なら、NaN を返す。
y > +0 𝔽 ならx を返す。
それ以外は-x を返す。
y が+∞ 𝔽 または-∞ 𝔽 なら、
x が+0 𝔽 または-0 𝔽 なら、NaN を返す。
x > +0 𝔽 ならy を返す。
それ以外は-y を返す。
x が-0 𝔽 なら、
y が-0 𝔽 またはy <
-0 𝔽 なら+0 𝔽 を返す。
それ以外は-0 𝔽 を返す。
y が-0 𝔽 なら、
x <
-0 𝔽 なら+0 𝔽 を返す。
それ以外は-0 𝔽 を返す。
𝔽 (ℝ (x ) ×
ℝ (y ))を返す。
注
有限 精度の乗算は可換だが、常に結合則が成り立つわけではありません。
6.1.6.1.5 Number::divide ( x , y )
抽象操作Number::divideは、引数x (Number型)、y (Number型)を受け取り、Number型を返します。IEEE
754-2019 の倍精度浮動小数点演算規則に従い、x を被除数、y を除数として商を計算します。呼び出し時、次の手順を実行します:
x がNaN またはy がNaN なら、NaN を返す。
x が+∞ 𝔽 または-∞ 𝔽 なら、
y が+∞ 𝔽 または-∞ 𝔽 なら、NaN を返す。
y が+0 𝔽 またはy >
+0 𝔽 ならx を返す。
それ以外は-x を返す。
y が+∞ 𝔽 なら、
x が+0 𝔽 またはx >
+0 𝔽 なら+0 𝔽 を返す。そうでなければ-0 𝔽 を返す。
y が-∞ 𝔽 なら、
x が+0 𝔽 またはx >
+0 𝔽 なら-0 𝔽 を返す。そうでなければ+0 𝔽 を返す。
x が+0 𝔽 または-0 𝔽 なら、
y が+0 𝔽 または-0 𝔽 なら、NaN を返す。
y > +0 𝔽 ならx を返す。
それ以外は-x を返す。
y が+0 𝔽 なら、
x >
+0 𝔽 なら+∞ 𝔽 を返す。そうでなければ-∞ 𝔽 を返す。
y が-0 𝔽 なら、
x >
+0 𝔽 なら-∞ 𝔽 を返す。そうでなければ+∞ 𝔽 を返す。
𝔽 (ℝ (x ) /
ℝ (y ))を返す。
6.1.6.1.6 Number::remainder ( n , d )
抽象操作Number::remainderは、引数n (Number型)、d (Number型)を受け取り、Number型を返します。ここでn は被除数、d は除数であり、暗黙の除算から余りを返します。呼び出し時、次の手順を実行します:
n がNaN またはd がNaN ならNaN を返す。
n が+∞ 𝔽 または-∞ 𝔽 ならNaN を返す。
d が+∞ 𝔽 または-∞ 𝔽 ならn を返す。
d が+0 𝔽 または-0 𝔽 ならNaN を返す。
n が+0 𝔽 または-0 𝔽 ならn を返す。
Assert :
n とd は有限 かつ非ゼロ。
quotient をℝ (n ) / ℝ (d )とする。
q をtruncate (quotient )とする。
r をℝ (n ) - (ℝ (d ) ×
q )とする。
r = 0かつn <
-0 𝔽 なら-0 𝔽 を返す。
𝔽 (r )を返す。
注1
CやC++では余り演算子は整数オペランドのみ受け付けますが、ECMAScriptでは浮動小数点オペランドも受け付けます。
注2
浮動小数点の余り演算(
%演算子で計算される)は、
IEEE
754-2019 で定義される“remainder”演算とは異なります。IEEE規格の“remainder”は丸め除算から余りを計算しますが、これは通常の
整数 余り演算子と類似しません。ECMAScript言語は、Javaの
整数 余り演算子と類似するように、浮動小数点演算での
%の挙動を定義しています。これはCライブラリ関数fmodと比較できます。
6.1.6.1.7 Number::add ( x , y )
抽象操作Number::addは、引数x (Number型)、y (Number型)を受け取り、Number型を返します。IEEE
754-2019 の倍精度浮動小数点演算規則に従い、引数の和を計算します。呼び出し時、次の手順を実行します:
x がNaN またはy がNaN なら、NaN を返す。
x が+∞ 𝔽 かつy が-∞ 𝔽 なら、NaN を返す。
x が-∞ 𝔽 かつy が+∞ 𝔽 なら、NaN を返す。
x が+∞ 𝔽 または-∞ 𝔽 なら、x を返す。
y が+∞ 𝔽 または-∞ 𝔽 なら、y を返す。
Assert :
x とy は両方とも有限 。
x が-0 𝔽 かつy が-0 𝔽 なら、-0 𝔽 を返す。
𝔽 (ℝ (x ) +
ℝ (y ))を返す。
注
有限 精度の加算は可換だが、常に結合則が成り立つわけではありません。
6.1.6.1.8 Number::subtract ( x , y )
抽象操作Number::subtractは、引数x (Number型)、y (Number型)を受け取り、Number型を返します。減算を行い、被減数x から減数y を引いた差を返します。呼び出し時、次の手順を実行します:
Number::add (x ,
Number::unaryMinus (y ))を返す。
注
常にx - yはx + (-y)と同じ結果を生成します。
6.1.6.1.9 Number::leftShift ( x , y )
抽象操作Number::leftShiftは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
lNum を! ToInt32 (x )とする。
rNum を! ToUint32 (y )とする。
shiftCount をℝ (rNum ) modulo 32とする。
lNum をshiftCount ビット左シフトした結果を返す。結果の数学値 は32ビット2の補数ビット列として正確に表現可能。
6.1.6.1.10 Number::signedRightShift ( x ,
y )
抽象操作Number::signedRightShiftは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
lNum を! ToInt32 (x )とする。
rNum を! ToUint32 (y )とする。
shiftCount をℝ (rNum ) modulo 32とする。
lNum をshiftCount ビット符号拡張付き右シフトした結果を返す。最上位ビットは伝播される。結果の数学値 は32ビット2の補数ビット列として正確に表現可能。
6.1.6.1.11 Number::unsignedRightShift ( x ,
y )
抽象操作Number::unsignedRightShiftは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
lNum を! ToUint32 (x )とする。
rNum を! ToUint32 (y )とする。
shiftCount をℝ (rNum ) modulo 32とする。
lNum をshiftCount ビットゼロ埋め右シフトした結果を返す。空いたビットはゼロで埋める。結果の数学値 は32ビット符号なしビット列として正確に表現可能。
6.1.6.1.12 Number::lessThan ( x , y )
抽象操作Number::lessThanは、引数x (Number型)、y (Number型)を受け取り、Booleanまたはundefined を返します。呼び出し時、次の手順を実行します:
x がNaN ならundefined を返す。
y がNaN ならundefined を返す。
x がy と等しければfalse を返す。
x が+0 𝔽 かつy が-0 𝔽 ならfalse を返す。
x が-0 𝔽 かつy が+0 𝔽 ならfalse を返す。
x が+∞ 𝔽 ならfalse を返す。
y が+∞ 𝔽 ならtrue を返す。
y が-∞ 𝔽 ならfalse を返す。
x が-∞ 𝔽 ならtrue を返す。
Assert :
x とy は有限 。
ℝ (x )
< ℝ (y )ならtrue 、そうでなければfalse を返す。
6.1.6.1.13 Number::equal ( x , y )
抽象操作Number::equalは、引数x (Number型)、y (Number型)を受け取り、Booleanを返します。呼び出し時、次の手順を実行します:
x がNaN ならfalse を返す。
y がNaN ならfalse を返す。
x がy と等しければtrue を返す。
x が+0 𝔽 かつy が-0 𝔽 ならtrue を返す。
x が-0 𝔽 かつy が+0 𝔽 ならtrue を返す。
false を返す。
6.1.6.1.14 Number::sameValue ( x , y )
抽象操作Number::sameValueは、引数x (Number型)、y (Number型)を受け取り、Booleanを返します。呼び出し時、次の手順を実行します:
x がNaN かつy がNaN ならtrue を返す。
x が+0 𝔽 かつy が-0 𝔽 ならfalse を返す。
x が-0 𝔽 かつy が+0 𝔽 ならfalse を返す。
x がy と等しければtrue を返す。
false を返す。
6.1.6.1.15 Number::sameValueZero ( x ,
y )
抽象操作Number::sameValueZeroは、引数x (Number型)、y (Number型)を受け取り、Booleanを返します。呼び出し時、次の手順を実行します:
x がNaN かつy がNaN ならtrue を返す。
x が+0 𝔽 かつy が-0 𝔽 ならtrue を返す。
x が-0 𝔽 かつy が+0 𝔽 ならtrue を返す。
x がy と等しければtrue を返す。
false を返す。
6.1.6.1.16 NumberBitwiseOp ( op , x ,
y )
抽象操作NumberBitwiseOpは、引数op (&、^、|)、x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
lNum を! ToInt32 (x )とする。
rNum を! ToInt32 (y )とする。
lBits をℝ (lNum )を表す32ビット2の補数ビット列とする。
rBits をℝ (rNum )を表す32ビット2の補数ビット列とする。
op が&なら、
result をlBits とrBits にビットAND演算を適用した結果とする。
そうでなくop が^なら、
result をlBits とrBits にビット排他的OR(XOR)演算を適用した結果とする。
それ以外の場合、
Assert :
op は|である。
result をlBits とrBits にビットOR演算を適用した結果とする。
result で表される32ビット2の補数ビット列の整数 に対応するNumber値 を返す。
6.1.6.1.17 Number::bitwiseAND ( x , y )
抽象操作Number::bitwiseANDは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
NumberBitwiseOp (&,
x , y )を返す。
6.1.6.1.18 Number::bitwiseXOR ( x , y )
抽象操作Number::bitwiseXORは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
NumberBitwiseOp (^,
x , y )を返す。
6.1.6.1.19 Number::bitwiseOR ( x , y )
抽象操作Number::bitwiseORは、引数x (Number型)、y (Number型)を受け取り、整数型Number を返します。呼び出し時、次の手順を実行します:
NumberBitwiseOp (|,
x , y )を返す。
6.1.6.1.20 Number::toString ( x , radix
)
抽象操作Number::toStringは、引数x (Number型)、radix (整数 で、2から36の包含区間 内)を受け取り、String型を返します。x を基数radix の位取り記数法で表現したString値として返します。基数r で数字として使うコード単位は、"0123456789abcdefghijklmnopqrstuvwxyz" の先頭r 個です。絶対値が1 𝔽 以上の数値は先頭ゼロを含みません。呼び出し時、次の手順を実行します:
x がNaN なら"NaN" を返す。
x が+0 𝔽 または-0 𝔽 なら"0" を返す。
x < -0 𝔽 なら、文字列連結 で"-" とNumber::toString (-x ,
radix )を連結して返す。
x が+∞ 𝔽 なら"Infinity" を返す。
n 、k 、s を整数 とし、k ≥
1、radix k - 1 ≤ s <
radix k 、𝔽 (s ×
radix n -
k )がx で、k が最小。k は基数radix で表現したs の桁数で、s はradix で割り切れず、最下位の桁は一意とは限らないことに注意。
radix ≠ 10またはn が-5から21の包含区間 なら、
n ≥ k なら、
基数radix で表現したs のk 桁のコード単位と、n
- k 個のコード単位0x0030(DIGIT ZERO)を文字列連結 して返す。
それ以外でn > 0なら、
基数radix で表現したs の最上位n 桁のコード単位、コード単位0x002E(FULL
STOP)、残りk - n 桁のコード単位を文字列連結 して返す。
それ以外、
Assert : n ≤ 0。
コード単位0x0030(DIGIT ZERO)、コード単位0x002E(FULL
STOP)、-n 個のコード単位0x0030(DIGIT
ZERO)、基数radix で表現したs のk 桁のコード単位を文字列連結 して返す。
この場合、入力は科学的E表記(例:1.2e+3)で表現される。
Assert :
radix は10。
n < 0なら、
exponentSign をコード単位0x002D(HYPHEN-MINUS)とする。
それ以外、
exponentSign をコード単位0x002B(PLUS SIGN)とする。
k = 1なら、
1桁のコード単位、コード単位0x0065(LATIN SMALL LETTER
E)、exponentSign 、abs (n -
1)の10進表現のコード単位を文字列連結 して返す。
最上位の10進桁のコード単位、コード単位0x002E(FULL STOP)、残りk -
1桁の10進表現のコード単位、コード単位0x0065(LATIN SMALL LETTER
E)、exponentSign 、abs (n -
1)の10進表現のコード単位を文字列連結 して返す。
注1
以下の観察事項は実装ガイドラインとして有用ですが、標準の規範要件ではありません:
注2
上記の規則よりも高精度な変換を提供する実装では、以下の代替バージョンの5 がガイドラインとして推奨されます:
n 、k 、s を整数 とし、k ≥
1、radix k - 1 ≤ s <
radix k 、𝔽 (s ×
radix n -
k )がx で、k が最小。s に複数の候補がある場合は、s
× radix n - k がℝ (x )に最も近い値を選択し、2つある場合は偶数を選ぶ。k は基数radix の桁数で、s はradix で割り切れないことに注意。
注3
ECMAScriptの実装者にはDavid M. Gayが書いた浮動小数点数の2進-10進変換の論文とコードが有用かもしれません:
Gay, David M. Correctly Rounded Binary-Decimal and Decimal-Binary Conversions.
Numerical Analysis, Manuscript 90-10. AT&T Bell Laboratories (Murray Hill,
New Jersey). 1990年11月30日。
https://ampl.com/_archive/first-website/REFS/rounding.pdf 。
関連コードは
http://netlib.sandia.gov/fp/dtoa.c
および
http://netlib.sandia.gov/fp/g_fmt.c
にあり、他のnetlibミラーサイトにもあります。
6.1.6.2 BigInt型
BigInt型 は、整数 値を表します。値は任意のサイズで、特定のビット幅に制限されません。特に記載がなければ、演算は正確な数学的結果を返すよう設計されています。2項演算では、BigIntは2の補数のバイナリ文字列として動作し、負の数は左側に無限にビットが立っているものとして扱われます。
6.1.6.2.1 BigInt::unaryMinus ( x )
抽象操作BigInt::unaryMinusは引数x (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
x =
0 ℤ なら0 ℤ を返す。
-x を返す。
6.1.6.2.2 BigInt::bitwiseNOT ( x )
抽象操作BigInt::bitwiseNOTは引数x (BigInt型)を受け取り、BigInt型を返します。x の1の補数を返します。呼び出し時、次の手順を実行します:
-x - 1 ℤ を返す。
6.1.6.2.3 BigInt::exponentiate ( base ,
exponent )
抽象操作BigInt::exponentiateは引数base (BigInt型)、exponent (BigInt型)を受け取り、正常完了(BigIntを含む) またはthrow
completion を返します。呼び出し時、次の手順を実行します:
exponent <
0 ℤ ならRangeError 例外を投げる。
base = 0 ℤ かつexponent =
0 ℤ なら1 ℤ を返す。
base のexponent 乗を返す。
6.1.6.2.4 BigInt::multiply ( x , y )
抽象操作BigInt::multiplyは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
x × y を返す。
注
結果が入力より遥かに大きなビット幅を持つ場合も、正確な数学解が返されます。
6.1.6.2.5 BigInt::divide ( x , y )
抽象操作BigInt::divideは引数x (BigInt型)、y (BigInt型)を受け取り、正常完了(BigIntを含む) またはthrow
completion を返します。呼び出し時、次の手順を実行します:
y =
0 ℤ ならRangeError 例外を投げる。
quotient をℝ (x ) / ℝ (y )とする。
ℤ (truncate (quotient ))を返す。
6.1.6.2.6 BigInt::remainder ( n , d )
抽象操作BigInt::remainderは引数n (BigInt型)、d (BigInt型)を受け取り、正常完了(BigIntを含む) またはthrow
completion を返します。呼び出し時、次の手順を実行します:
d =
0 ℤ ならRangeError 例外を投げる。
n =
0 ℤ なら0 ℤ を返す。
quotient をℝ (n ) / ℝ (d )とする。
q をℤ (truncate (quotient ))とする。
n - (d × q )を返す。
注
結果の符号は被除数の符号になります。
6.1.6.2.7 BigInt::add ( x , y )
抽象操作BigInt::addは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
x + y を返す。
6.1.6.2.8 BigInt::subtract ( x , y )
抽象操作BigInt::subtractは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
x - y を返す。
6.1.6.2.9 BigInt::leftShift ( x , y )
抽象操作BigInt::leftShiftは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
y < 0 ℤ なら、
ℤ (floor (ℝ (x )
/ 2-ℝ (y ) ))を返す。
x × 2 ℤ y を返す。
注
ここでの意味論は、BigIntを無限長の2の補数バイナリ列としてビットシフトした場合と同等です。
6.1.6.2.10 BigInt::signedRightShift ( x ,
y )
抽象操作BigInt::signedRightShiftは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
BigInt::leftShift (x ,
-y )を返す。
6.1.6.2.11 BigInt::unsignedRightShift ( x ,
y )
抽象操作BigInt::unsignedRightShiftは引数x (BigInt型)、y (BigInt型)を受け取り、throw
completion を返します。呼び出し時、次の手順を実行します:
TypeError 例外を投げる。
6.1.6.2.12 BigInt::lessThan ( x , y )
抽象操作BigInt::lessThanは引数x (BigInt型)、y (BigInt型)を受け取り、Boolean型を返します。呼び出し時、次の手順を実行します:
ℝ (x )
< ℝ (y )ならtrue 、そうでなければfalse を返す。
6.1.6.2.13 BigInt::equal ( x , y )
抽象操作BigInt::equalは引数x (BigInt型)、y (BigInt型)を受け取り、Boolean型を返します。呼び出し時、次の手順を実行します:
ℝ (x ) =
ℝ (y )ならtrue 、そうでなければfalse を返す。
6.1.6.2.14 BinaryAnd ( x , y )
抽象操作BinaryAndは引数x (0または1)、y (0または1)を受け取り、0または1を返します。呼び出し時、次の手順を実行します:
x = 1かつy = 1なら1を返す。
それ以外は0を返す。
6.1.6.2.15 BinaryOr ( x , y )
抽象操作BinaryOrは引数x (0または1)、y (0または1)を受け取り、0または1を返します。呼び出し時、次の手順を実行します:
x = 1またはy = 1なら1を返す。
それ以外は0を返す。
6.1.6.2.16 BinaryXor ( x , y )
抽象操作BinaryXorは引数x (0または1)、y (0または1)を受け取り、0または1を返します。呼び出し時、次の手順を実行します:
x = 1かつy = 0なら1を返す。
それ以外でx = 0かつy = 1なら1を返す。
それ以外は0を返す。
6.1.6.2.17 BigIntBitwiseOp ( op , x ,
y )
抽象操作BigIntBitwiseOpは、引数op (&、^、|)、x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
x をℝ (x )に設定する。
y をℝ (y )に設定する。
result を0に設定する。
shift を0に設定する。
次を満たすまで繰り返す:(x = 0またはx = -1)かつ(y =
0またはy = -1)
xDigit をx modulo 2とする。
yDigit をy modulo 2とする。
op が&なら、
result をresult +
2shift × BinaryAnd (xDigit ,
yDigit )に設定する。
それ以外でop が|なら、
result をresult +
2shift × BinaryOr (xDigit ,
yDigit )に設定する。
それ以外の場合、
Assert :
op は^である。
result をresult +
2shift × BinaryXor (xDigit ,
yDigit )に設定する。
shift をshift + 1に設定する。
x を(x - xDigit ) / 2に設定する。
y を(y - yDigit ) / 2に設定する。
op が&なら、
tmp をBinaryAnd (x
modulo 2, y
modulo 2)に設定する。
それ以外でop が|なら、
tmp をBinaryOr (x
modulo 2, y
modulo 2)に設定する。
それ以外の場合、
Assert :
op は^である。
tmp をBinaryXor (x
modulo 2, y
modulo 2)に設定する。
tmp ≠ 0なら、
result をresult - 2shift に設定する。
注:これは符号拡張を行います。
result のBigInt値 を返す。
6.1.6.2.18 BigInt::bitwiseAND ( x , y )
抽象操作BigInt::bitwiseANDは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
BigIntBitwiseOp (&,
x , y )を返す。
6.1.6.2.19 BigInt::bitwiseXOR ( x , y )
抽象操作BigInt::bitwiseXORは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
BigIntBitwiseOp (^,
x , y )を返す。
6.1.6.2.20 BigInt::bitwiseOR ( x , y )
抽象操作BigInt::bitwiseORは引数x (BigInt型)、y (BigInt型)を受け取り、BigInt型を返します。呼び出し時、次の手順を実行します:
BigIntBitwiseOp (|,
x , y )を返す。
6.1.6.2.21 BigInt::toString ( x , radix
)
抽象操作BigInt::toStringは引数x (BigInt型)、radix (整数 で、2から36の包含区間 内)を受け取り、String型を返します。x を基数radix の位取り記数法で表現したString値として返します。基数r で数字として使うコード単位は、"0123456789abcdefghijklmnopqrstuvwxyz" の先頭r 個です。0 ℤ 以外のBigInt表現は先頭ゼロを含みません。呼び出し時、次の手順を実行します:
x < 0 ℤ なら、文字列連結 で"-" とBigInt::toString (-x ,
radix )を連結して返す。
基数radix で表現したx のString値を返す。
6.1.7 オブジェクト型
Object型 の各インスタンス(単に「オブジェクト」とも呼ばれる)は、プロパティの集合を表します。各プロパティはデータプロパティまたはアクセサプロパティのいずれかです:
データプロパティ は、キー値をECMAScript言語値 とBoolean属性の集合に関連付けます。
アクセサプロパティ は、キー値を1つまたは2つのアクセサ関数とBoolean属性の集合に関連付けます。アクセサ関数は、そのプロパティに関連付けられたECMAScript言語値 の格納や取得に使われます。
オブジェクトのプロパティはプロパティキー で一意に識別されます。 プロパティキー はStringまたはSymbolです。空文字列を含むすべてのStringおよびSymbolはプロパティキー として有効です。プロパティ名 は、プロパティキー で、String型であるもの です。
整数インデックス は、プロパティ名 n で、CanonicalNumericIndexString (n )
が整数型Number で、+0𝔽 から𝔽 (253 -
1)までの包含区間 にあるものです。配列インデックス は、整数インデックス n で、CanonicalNumericIndexString (n )
が整数型Number で、+0𝔽 から𝔽 (232 -
2)までの包含区間 にあるものです。
注
すべての非負の安全な整数 には対応する整数インデックス があります。すべての32ビット符号なし整数 (ただし232 - 1 を除く)には対応する配列インデックス があります。"-0" は整数インデックス でも配列インデックス でもありません。
プロパティキー はプロパティやその値へのアクセスに使われます。プロパティへのアクセスにはget とset の2種類があり、それぞれ値の取得と代入に対応します。get/setアクセス可能なプロパティには、オブジェクト自身が直接持つ所有プロパティ と、他の関連オブジェクトから継承される継承プロパティ の両方が含まれます。継承プロパティは、関連オブジェクトの所有プロパティまたはその継承プロパティのいずれかです。オブジェクトの各所有プロパティは、他の所有プロパティのキー値とは異なるキー値を持たなければなりません。
すべてのオブジェクトは論理的にプロパティの集合ですが、プロパティのアクセスや操作の意味論が異なる複数の形式のオブジェクトが存在します。詳細は6.1.7.2 を参照してください。
さらに、一部のオブジェクトは呼び出し可能であり、これらは関数または関数オブジェクト と呼ばれ、後述で説明されます。ECMAScriptのすべての関数はObject型のメンバーです。
6.1.7.1 プロパティ属性
属性は、この仕様でObjectプロパティの状態を定義・説明するために使用されます(表3 参照)。明示的な指定がない限り、各属性の初期値はデフォルト値です。
表3: オブジェクトプロパティの属性
属性名
属性が存在するプロパティの種類
値のドメイン
デフォルト値
説明
[[Value]]
データプロパティ
ECMAScript言語値
undefined
getアクセスで取得されるプロパティの値。
[[Writable]]
データプロパティ
Boolean
false
false の場合、ECMAScriptコードによる[[Set]] で[[Value]] 属性を変更しようとしても成功しません。
[[Get]]
アクセサプロパティ
Object または undefined
undefined
値がObject の場合は関数オブジェクト でなければなりません。関数の[[Call]] 内部メソッド(表5 )が引数なしで呼び出され、プロパティ値を取得します。
[[Set]]
アクセサプロパティ
Object または undefined
undefined
値がObject の場合は関数オブジェクト でなければなりません。関数の[[Call]] 内部メソッド(表5 )が、代入値を唯一の引数とする引数リストで呼び出されます。[[Set]] の効果は、必須ではありませんが、以降の[[Get]] の結果に影響する場合があります。
[[Enumerable]]
データプロパティ または
アクセサプロパティ
Boolean
false
true の場合、このプロパティはfor-in列挙(14.7.5 参照)で列挙されます。それ以外の場合、非列挙プロパティとみなされます。
[[Configurable]]
データプロパティ または
アクセサプロパティ
Boolean
false
false の場合、プロパティの削除、データプロパティからアクセサプロパティへの変更、またはその逆、既存[[Value]] の置き換えや[[Writable]] をfalse に設定する以外の属性変更は失敗します。
6.1.7.2 オブジェクトの内部メソッドと内部スロット
ECMAScriptにおけるオブジェクトの実際の意味論は、内部メソッド と呼ばれるアルゴリズムによって規定されます。ECMAScriptエンジンの各オブジェクトには、その実行時の挙動を定義する内部メソッドの集合が関連付けられています。これらの内部メソッドはECMAScript言語の一部ではありません。本仕様で説明目的のみで定義されます。ただし、ECMAScriptの各実装におけるオブジェクトは、その関連付けられた内部メソッドで規定されたとおりに動作しなければなりません。その実現方法の詳細は実装によって決まります。
内部メソッド名はポリモーフィックです。つまり、同じ内部メソッド名を呼び出しても、異なるオブジェクト値ごとに異なるアルゴリズムが実行される場合があります。内部メソッドが呼び出される実際のオブジェクトを「ターゲット」と呼びます。実行時に、あるアルゴリズムがオブジェクトのサポートしない内部メソッドを使おうとした場合、TypeError 例外がスローされます。
内部スロットは、オブジェクトに関連付けられ、ECMAScript仕様のさまざまなアルゴリズムで使われる内部状態を表します。内部スロットはオブジェクトのプロパティではなく、継承もされません。各内部スロット仕様によっては、その状態はどのECMAScript言語型 や特定のECMAScript仕様型値でもかまいません。特に指定がなければ、内部スロットはオブジェクト生成時に割り当てられ、動的に追加することはできません。特に指定がなければ、内部スロットの初期値はundefined です。本仕様内のさまざまなアルゴリズムで内部スロットを持つオブジェクトが作られますが、ECMAScript言語では内部スロットを直接オブジェクトに関連付ける方法はありません。
すべてのオブジェクトには[[PrivateElements]] という名前の内部スロットがあり、これはList 型で、PrivateElements が入ります。このList は、そのオブジェクトのプライベートフィールド・メソッド・アクセサの値を表します。初期状態では空のList です。
内部メソッドと内部スロットは、この仕様では[[ ]]で囲まれた名前で示されます。
表4 は、ECMAScriptコードにより作成または操作されるすべてのオブジェクトに適用される、本仕様で使用される本質的内部メソッド をまとめたものです。すべてのオブジェクトは、すべての本質的内部メソッドに対するアルゴリズムを持たなければなりません。ただし、すべてのオブジェクトがそれらすべてに同じアルゴリズムを使うとは限りません。
通常のオブジェクト とは、次の条件をすべて満たすオブジェクトです:
表4 に挙げた内部メソッドについて、そのオブジェクトは10.1 で定義されたものを使う。
オブジェクトが[[Call]] 内部メソッドを持つ場合、それは10.2.1 または10.3.1 で定義されたもののいずれかを使う。
オブジェクトが[[Construct]] 内部メソッドを持つ場合、それは10.2.2 または10.3.2 で定義されたもののいずれかを使う。
エキゾチックオブジェクト とは、通常のオブジェクト でないオブジェクトです。
本仕様では、エキゾチックオブジェクト の種類ごとに、そのオブジェクトの内部メソッドで区別しています。特定の種類のエキゾチックオブジェクト (例えば配列エキゾチックオブジェクト やバウンド関数エキゾチックオブジェクト )と動作上同等でも、当該種類で規定された内部メソッド群を持たなければ、その種類のエキゾチックオブジェクト とは認められません。
表4 や類似表の「Signature」列では、各内部メソッドの呼び出しパターンを記載しています。呼び出しパターンには常にパラメータ名の括弧付きリストが含まれます。パラメータ名がECMAScript型名と同じ場合、その値の型を示します。内部メソッドが明示的に値を返す場合、パラメータリストの後に「→」と戻り値型を記載します。型名は6 節で定義された型に、以下の追加型を加えたものです。「any 」は任意のECMAScript言語型 であることを意味します。
内部メソッドは、パラメータに加えて、常に呼び出し対象のオブジェクト自身にアクセスできます。
内部メソッドは暗黙的にCompletion
Record を返します。これは、呼び出しパターンで示す戻り値型を包んだnormal
completion か、throw
completion のいずれかです。
表4: 本質的内部メソッド
内部メソッド
シグネチャ
説明
[[GetPrototypeOf]]
( ) → Object | Null
このオブジェクトに継承プロパティを提供するオブジェクトを決定する。null 値は継承プロパティが存在しないことを示す。
[[SetPrototypeOf]]
(Object | Null) → Boolean
このオブジェクトに継承プロパティを提供する別のオブジェクトを関連付ける。null を渡すと継承プロパティがないことになる。操作が成功した場合はtrue 、失敗した場合はfalse を返す。
[[IsExtensible]]
( ) → Boolean
このオブジェクトに追加プロパティを追加できるかどうかを判定する。
[[PreventExtensions]]
( ) → Boolean
このオブジェクトに新たなプロパティを追加できるかどうかを制御する。操作が成功したらtrue 、失敗したらfalse を返す。
[[GetOwnProperty]]
(propertyKey ) → Undefined | Property
Descriptor
このオブジェクトの所有プロパティでキーがpropertyKey であるものについて、Property
Descriptor を返す。該当プロパティがなければundefined を返す。
[[DefineOwnProperty]]
(propertyKey , PropertyDescriptor ) → Boolean
キーがpropertyKey の所有プロパティをPropertyDescriptor で記述される状態に新規作成または変更する。プロパティの作成・更新に成功した場合はtrue 、失敗した場合はfalse を返す。
[[HasProperty]]
(propertyKey ) → Boolean
このオブジェクトが既に所有または継承するキーpropertyKey のプロパティを持つかどうかを示すBoolean値を返す。
[[Get]]
(propertyKey , Receiver ) → any
このオブジェクトからキーpropertyKey のプロパティ値を返す。プロパティ値の取得にECMAScriptコードの実行が必要な場合、Receiver がthis 値として使われる。
[[Set]]
(propertyKey , value , Receiver ) →
Boolean
このオブジェクトのキーpropertyKey のプロパティ値をvalue に設定する。値の設定にECMAScriptコードの実行が必要な場合、Receiver がthis 値として使われる。値の設定に成功したらtrue 、失敗したらfalse を返す。
[[Delete]]
(propertyKey ) → Boolean
このオブジェクトからキーpropertyKey の所有プロパティを削除する。削除できなかった場合(まだ存在する場合)はfalse 、削除できた場合またはプロパティが存在しない場合はtrue を返す。
[[OwnPropertyKeys]]
( ) → List
of property keys
オブジェクトのすべての所有プロパティキー を要素とするList を返す。
表5 は、関数として呼び出し可能なオブジェクトがサポートする追加の本質的内部メソッドをまとめたものです。関数オブジェクト は[[Call]] 内部メソッドをサポートするオブジェクトです。コンストラクタ は[[Construct]] 内部メソッドをサポートするオブジェクトです。[[Construct]] をサポートするすべてのオブジェクトは[[Call]] もサポートしなければなりません。つまり、すべてのコンストラクタ は関数オブジェクト でなければなりません。したがって、コンストラクタ はコンストラクタ関数 またはコンストラクタ 関数オブジェクト とも呼ばれます。
表5: 関数オブジェクトの追加本質的内部メソッド
内部メソッド
シグネチャ
説明
[[Call]]
(any , any型のList )
→ any
このオブジェクトに関連するコードを実行する。関数呼び出し式を介して呼び出される。内部メソッドの引数はthis 値と、呼び出し式で関数に渡された引数を要素とするList 。この内部メソッドを実装するオブジェクトは呼び出し可能 である。
[[Construct]]
(any型のList ,
Object)
→ Object
オブジェクトを生成する。new演算子またはsuper呼び出しで呼ばれる。内部メソッドの第1引数はコンストラクタ 呼び出しまたはsuper呼び出しの引数を要素とするList 。第2引数はnew演算子が最初に適用されたオブジェクト。これを実装するオブジェクトはコンストラクタ と呼ばれる。関数オブジェクト が必ずしもコンストラクタ とは限らず、コンストラクタでない関数オブジェクト は[[Construct]] 内部メソッドを持ちません。
通常のオブジェクト および標準的な
エキゾチックオブジェクト の本質的内部メソッドの意味論は、10 節で規定されています。エキゾチックオブジェクト の内部メソッドの指定された使用が実装でサポートされていない場合、その使用を試みるとTypeError 例外をスローしなければなりません。
6.1.7.3 本質的内部メソッドの不変条件
ECMAScriptエンジンのオブジェクトの内部メソッドは、以下に指定する不変条件を満たさなければなりません。本仕様の通常のECMAScriptオブジェクトおよびすべての標準エキゾチックオブジェクト はこれらの不変条件を維持します。ECMAScript
Proxyオブジェクトは、[[ProxyHandler]] オブジェクト上のトラップ呼び出し結果に対する実行時チェックによって、これらの不変条件を維持します。
実装で提供されるエキゾチックオブジェクト も、それらについてこれらの不変条件を維持しなければなりません。不変条件違反は、ECMAScriptコードが予測不可能な動作をしたり、セキュリティ上の問題を引き起こす可能性があります。しかし、不変条件の違反によって実装のメモリ安全性が損なわれてはなりません。
実装は、必須内部メソッドの機能を不変条件を強制せずに別のインターフェースで提供するといった手段で、これらの不変条件を回避できるようにしてはなりません。
定義:
内部メソッドのターゲット とは、その内部メソッドが呼び出されるオブジェクトです。
ターゲットの[[IsExtensible]] 内部メソッドがfalse を返した、または[[PreventExtensions]] 内部メソッドがtrue を返したことが観測された場合、ターゲットは拡張不可(non-extensible) です。
存在しない(non-existent) プロパティとは、拡張不可ターゲットの所有プロパティとして存在しないプロパティです。
SameValue へのすべての参照は、SameValue アルゴリズムの定義によります。
戻り値:
いかなる内部メソッドが返す値も、以下のいずれかのCompletion
Record でなければなりません:
[[Type]] = normal 、[[Target]] = empty 、[[Value]] = 下記に示すその内部メソッドの「通常の戻り値型」の値、または
[[Type]] = throw 、[[Target]] = empty 、[[Value]] = 任意のECMAScript言語値 。
注1
[[GetPrototypeOf]] ( )
通常の戻り値型はObjectまたはNullです。
ターゲットが拡張不可で[[GetPrototypeOf]] が値V を返した場合、以後の[[GetPrototypeOf]] 呼び出しもSameValue としてV を返すべきです。
注2
オブジェクトのプロトタイプチェーンは有限 長であるべきです(すなわち、任意のオブジェクトから再帰的に[[GetPrototypeOf]] 内部メソッドを適用していけば最終的にnull に到達する)が、プロトタイプチェーンに通常のオブジェクト の定義によらないエキゾチックオブジェクト が含まれる場合、この要件はオブジェクトレベルの不変条件として強制できません。そのような循環プロトタイプチェーンは、プロパティアクセス時に無限ループを引き起こすことがあります。
[[SetPrototypeOf]] ( V )
通常の戻り値型はBooleanです。
ターゲットが拡張不可の場合、V がターゲットの観測された[[GetPrototypeOf]] 値とSameValue でない限り、[[SetPrototypeOf]] はfalse を返さなければなりません。
[[IsExtensible]] ( )
通常の戻り値型はBooleanです。
[[IsExtensible]] がfalse を返した場合、それ以降のターゲットへの[[IsExtensible]] 呼び出しはすべてfalse を返さなければなりません。
[[PreventExtensions]] ( )
通常の戻り値型はBooleanです。
[[PreventExtensions]] がtrue を返した場合、それ以降のターゲットへの[[IsExtensible]] 呼び出しはすべてfalse を返し、ターゲットは拡張不可とみなされます。
[[GetOwnProperty]] ( P )
通常の戻り値型はProperty
Descriptor またはUndefinedです。
戻り値がProperty
Descriptor の場合、それは完全なProperty
Descriptor でなければなりません。
P が非設定可能かつ非書換可能な所有データプロパティ である場合、以後の[[GetOwnProperty]] (P )呼び出しは、[[Value]] がSameValue でP の[[Value]] 属性と一致するProperty
Descriptor を返さなければなりません。
P の[[Writable]] ・[[Value]] 以外の属性が将来変更される、またはプロパティが削除される可能性がある場合、[[Configurable]] 属性はtrue でなければなりません。
[[Writable]] 属性がfalse からtrue に将来変更される可能性がある場合、[[Configurable]] 属性はtrue でなければなりません。
ターゲットが拡張不可でP が存在しない場合、以後のターゲットへの[[GetOwnProperty]] (P )呼び出しはP が存在しないものとして記述しなければなりません(つまり[[GetOwnProperty]] (P )はundefined を返さなければなりません)。
注3
第3不変条件の帰結として、プロパティがデータプロパティ であり、値が将来変化する可能性がある場合は、他の本質的内部メソッドで値の変更機構が提供されていなくても、[[Writable]] ・[[Configurable]] 属性のいずれかまたは両方がtrue でなければなりません。
[[DefineOwnProperty]] ( P , Desc )
通常の戻り値型はBooleanです。
[[DefineOwnProperty]] は、P が以前に非設定可能な所有プロパティとして観測されていた場合、次のいずれかを除きfalse を返さなければなりません:
P が書き換え可能なデータプロパティ である。非設定可能な書き換え可能データプロパティは、非設定可能な非書き換え可能データプロパティに変更できる。
Desc のすべての属性がP の属性とSameValue である。
[[DefineOwnProperty]] (P ,
Desc )は、ターゲットが拡張不可かつP が存在しない所有プロパティの場合false を返さなければなりません。つまり、拡張不可なターゲットオブジェクトは新たなプロパティで拡張できません。
[[HasProperty]] ( P )
通常の戻り値型はBooleanです。
P が以前にターゲットの非設定可能な所有データまたはアクセサプロパティ として観測されていた場合、[[HasProperty]] はtrue を返さなければなりません。
[[Get]] ( P , Receiver )
通常の戻り値型はECMAScript言語型 です。
P が以前にターゲットの非設定可能・非書換可能な所有データプロパティ で値V を持つと観測されていた場合、[[Get]] はV とSameValue な値を返さなければなりません。
P が以前にターゲットの非設定可能な所有アクセサプロパティ で、その[[Get]] 属性がundefined だった場合、[[Get]] 操作はundefined を返さなければなりません。
[[Set]] ( P , V , Receiver )
通常の戻り値型はBooleanです。
P が以前にターゲットの非設定可能・非書換可能な所有データプロパティ であった場合、[[Set]] はV がP の[[Value]] 属性とSameValue でない限りfalse を返さなければなりません。
P が以前にターゲットの非設定可能な所有アクセサプロパティ で、その[[Set]] 属性がundefined だった場合、[[Set]] 操作はfalse を返さなければなりません。
[[Delete]] ( P )
通常の戻り値型はBooleanです。
P が以前にターゲットの非設定可能な所有データまたはアクセサプロパティ であった場合、[[Delete]] はfalse を返さなければなりません。
[[OwnPropertyKeys]] ( )
通常の戻り値型はList です。
返されるList には重複要素があってはなりません。
返されるList の各要素は、プロパティキー でなければなりません。
返されるList には、これまでに観測されたすべての非設定可能な所有プロパティのキーが少なくとも含まれていなければなりません。
ターゲットが拡張不可の場合、返されるList には[[GetOwnProperty]] で観測可能なターゲットのすべての所有プロパティのキーのみが含まれていなければなりません。
[[Call]] ( )
[[Construct]] ( )
通常の戻り値型はObjectです。
ターゲットは[[Call]] 内部メソッドも持っていなければなりません。
6.1.7.4 よく知られた組み込みオブジェクト
よく知られた組み込みオブジェクトは、この仕様書のアルゴリズムで明示的に参照される組み込みオブジェクトであり、通常はrealm 固有の識別子を持ちます。特に指定がない限り、各組み込みオブジェクトは実際には似たオブジェクトのセットに対応しており、realm ごとに1つ存在します。
この仕様書内では、%name% のような参照は、現在のrealm に関連付けられた、nameに対応する組み込みオブジェクトを意味します。%name.a.b%
のような参照は、ECMAScriptコードが評価される前に、組み込みオブジェクト %name% の "a" プロパティの値の
"b" プロパティにアクセスしたかのような意味になります。現在のrealm およびその組み込みオブジェクトの決定方法については、9.4 で説明されています。よく知られた組み込みオブジェクトは、表6 に一覧されています。
表6: よく知られた組み込みオブジェクト
注
6.2 ECMAScript 仕様タイプ
仕様タイプは、アルゴリズム内で ECMAScript 言語構成要素および ECMAScript 言語タイプ
のセマンティクスを記述するために使用されるメタ値に対応します。仕様タイプには、Reference
Record 、List 、Completion Record 、Property Descriptor 、
Environment Record 、Abstract
Closure 、および Data Block が含まれます。仕様タイプ値は、仕様上の成果物であり、ECMAScript
実装内の特定の実体に必ずしも対応しません。仕様タイプ値は、ECMAScript 式評価の中間結果を記述するために使用される場合がありますが、そのような値をオブジェクトのプロパティや
ECMAScript 言語変数の値として格納することはできません。
6.2.1 Enum 仕様タイプ
Enum は仕様内部でのみ使用され、ECMAScript コードから直接観測できない値です。Enum
は sans-serif 書体で表記されます。たとえば、Completion Record の [[Type]] フィールドは
normal 、return 、throw
などの値をとります。Enum にはその名前以外の特徴はなく、Enum の名前は他の Enum との区別のためだけに用いられ、その用途や意味については何も示しません。
6.2.2 List および Record 仕様タイプ
List 型は、new
式、関数呼び出し、その他のアルゴリズムで引数リスト(13.3.8
参照)の評価を説明するため、および値の単純な順序付きリストが必要な場合に使用されます。List
型の値は、個々の値を含むリスト要素の順序付きシーケンスです。これらのシーケンスは任意の長さにできます。リストの要素は、0
オリジンのインデックスを使ってランダムアクセスできます。記法上の便宜のため、配列風の構文で List 要素へアクセスすることができます。例えば、arguments [2]
は、List arguments の 3 番目の要素を示します。
アルゴリズムが List の要素を順序を明示せずに反復する場合、その順序は List の要素順です。
この仕様内では、リテラル構文で新しい List 値を表現できます。例えば、« 1, 2 » は 2 つの要素を持つ List 値を表し、それぞれ特定の値で初期化されます。新しい空の List は
« » で表現できます。
この仕様書では、「A , B , ... の list-concatenation 」という表現(各引数は空の場合もある List)で、各引数の要素を(順に)連結した新しい List
値を意味します。
List of Strings に対して、「辞書式コードユニット順 でソートする」とは、短い方の文字列の長さまで各コードユニットの数値値でソートし、すべて等しい場合は短い文字列を先に並べることを意味します。これは抽象操作
IsLessThan
で説明されています。
Record 型は、この仕様のアルゴリズム内でデータの集約を記述するために使用されます。Record
型の値は 1 つ以上の名前付きフィールドからなります。各フィールドの値は ECMAScript 言語値
または仕様値です。フィールド名は常に二重括弧で囲まれます。例:[[Value]] 。
この仕様内ではオブジェクトリテラル風の構文で Record 値を表現できます。たとえば、{ [[Field1]] : 42, [[Field2]] : false , [[Field3]] :
empty } は 3 つのフィールドを持つ Record
値を定義し、それぞれ特定の値で初期化されます。フィールド名の順序に意味はありません。明示的にリストされていないフィールドは存在しないものとみなされます。
仕様テキストやアルゴリズムでは、Record 値の特定のフィールドを参照するためにドット記法を使うことがあります。たとえば、前述の R というレコードに対して R.[[Field2]] は「R の [[Field2]] という名前のフィールド」を意味します。
よく使われる Record フィールドの組み合わせのスキーマには名前を付けることができ、その名前をリテラル Record
値の前に付与して、どの種類の集約が記述されているかを明示できます。例:PropertyDescriptor { [[Value]] : 42,
[[Writable]] : false , [[Configurable]] : true }。
6.2.3 Set および Relation 仕様タイプ
Set 型は、メモリーモデル で使用する無順序要素の集合を説明するために使われます。これは同名の
ECMAScript コレクション型とは異なります。区別のため、この仕様内では ECMAScript のコレクションのインスタンスは一貫して「Set オブジェクト」と呼ばれます。Set
型の値は単純な要素のコレクションで、同じ要素が複数回現れることはありません。要素は Set へ追加・削除できます。Set 同士は和集合・積集合・差集合の演算ができます。
Relation 型は、Set 上の制約を説明するために使われます。Relation
型の値は、その値領域の順序付きペアの Set です。たとえば、イベント上の Relation はイベントの順序付きペアの集合です。Relation R
およびその値領域内の 2 つの値 a 、b に対し、a R b は順序付きペア
(a , b ) が R の要素であることを略記しています。Relation は、ある条件に対してそれを満たす最小の
Relation(最小 Relation )である場合、その条件に関する最小の Relation です。
狭義半順序(strict partial order) とは、Relation
値 R が次を満たすことです。
注1
上記2つの性質は、それぞれ反射性なし(irreflexivity)・推移性(transitivity)と呼ばれます。
狭義全順序(strict total order) とは、Relation 値
R が次を満たすことです。
注2
上記3つの性質は、それぞれ全順序性(totality)・反射性なし(irreflexivity)・推移性(transitivity)と呼ばれます。
6.2.4 完了レコード仕様タイプ
Completion Record
仕様タイプは、値のランタイム伝播や、break、continue、return、throw
など、制御の非局所的な移動を行う文の動作など、制御フローを説明するために用いられます。
Completion Record には 表7 で定義されているフィールドがあります。
表7: Completion
Record のフィールド
フィールド名
値
意味
[[Type]]
normal , break ,
continue , return , または
throw
発生した完了の種類。
[[Value]]
Completion
Record 以外の任意の値
生成された値。
[[Target]]
文字列または empty
指定された制御移動のターゲットラベル。
Completion Record を指すために、以下のような略語が使われることがあります。
normal completion は、[[Type]] の値が normal である Completion Record
を指します。
break completion は、[[Type]] の値が break である Completion Record
を指します。
continue completion は、[[Type]] の値が continue である Completion Record
を指します。
return completion は、[[Type]] の値が return である Completion Record
を指します。
throw completion は、[[Type]] の値が throw である Completion Record
を指します。
abrupt completion は、[[Type]] の値が normal 以外である Completion Record
を指します。
normal completion
containing ある型の値を含む normal completion とは、その型の値が [[Value]]
フィールドにある normal completion を指します。
この仕様で定義される呼び出し可能オブジェクトは、normal completion または throw completion のみを返します。それ以外の Completion Record
を返すことは編集上の誤りとみなされます。
実装依存 の呼び出し可能オブジェクトも normal completion または
throw completion のいずれかを返さなければなりません。
6.2.4.1 NormalCompletion ( value )
抽象操作 NormalCompletion は、引数 value (Completion Record
以外の任意の値)を受け取り、normal completion
を返します。呼び出されたとき、次の手順を実行します。
Completion
Record { [[Type]] :
normal , [[Value]] : value ,
[[Target]] : empty } を返す。
6.2.4.2 ThrowCompletion ( value )
抽象操作 ThrowCompletion は、引数 value (ECMAScript
言語値 )を受け取り、throw
completion を返します。呼び出されたとき、次の手順を実行します。
Completion
Record { [[Type]] :
throw , [[Value]] : value ,
[[Target]] : empty } を返す。
6.2.4.3 ReturnCompletion ( value )
抽象操作 ReturnCompletion は、引数 value (ECMAScript
言語値 )を受け取り、return
completion を返します。呼び出されたとき、次の手順を実行します。
Completion
Record { [[Type]] :
return , [[Value]] : value ,
[[Target]] : empty } を返す。
6.2.4.4 UpdateEmpty ( completionRecord ,
value )
抽象操作 UpdateEmpty は、引数 completionRecord (Completion Record )と
value (Completion
Record 以外の任意の値)を受け取り、Completion Record
を返します。呼び出されたとき、次の手順を実行します。
アサート :
completionRecord が return
completion または throw
completion のいずれかである場合、completionRecord .[[Value]] は empty であってはならない。
もし completionRecord .[[Value]] が
empty でなければ、? completionRecord を返す。
Completion
Record { [[Type]] :
completionRecord .[[Type]] , [[Value]] : value , [[Target]] : completionRecord .[[Target]] } を返す。
6.2.5 参照レコード仕様タイプ
Reference Record
型は、delete、typeof、代入演算子、super キーワード 、その他の言語機能の動作を説明するために使用されます。例えば、代入の左辺値は
Reference Record を生成することが期待されます。
Reference Record は解決された名前または(まだ解決されていないかもしれない)プロパティバインディングであり、そのフィールドは 表8 で定義されています。
表8: Reference
Record のフィールド
この仕様で参照レコードを操作するために、以下の 抽象操作
が使用されます。
6.2.5.1 IsPropertyReference ( V )
抽象操作 IsPropertyReference は、引数 V (Reference
Record )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します。
もし V .[[Base]] が
unresolvable なら、false を返す。
もし V .[[Base]] が Environment Record なら
false を返し、それ以外なら true を返す。
6.2.5.2 IsUnresolvableReference ( V )
抽象操作 IsUnresolvableReference は、引数 V (Reference
Record )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します。
もし V .[[Base]] が
unresolvable なら true を返し、それ以外なら
false を返す。
6.2.5.3 IsSuperReference ( V )
抽象操作 IsSuperReference は、引数 V (Reference
Record )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します。
もし V .[[ThisValue]] が
empty でなければ true を返し、それ以外なら
false を返す。
6.2.5.4 IsPrivateReference ( V )
抽象操作 IsPrivateReference は、引数 V (Reference
Record )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します。
もし V .[[ReferencedName]] がPrivate
Name であれば true を返し、それ以外なら
false を返す。
6.2.5.5 GetValue ( V )
抽象操作 GetValue は、引数 V (Reference
Record または
ECMAScript 言語値 )を受け取り、normal completion
containing な ECMAScript 言語値
か、abrupt completion
のいずれかを返します。呼び出されたとき、次の手順を実行します。
もし V が Reference
Record でなければ、V を返す。
IsUnresolvableReference (V )
が true なら、ReferenceError 例外をスローする。
IsPropertyReference (V )
が true なら、
baseObj を ? ToObject (V .[[Base]] ) とする。
IsPrivateReference (V )
が true なら、
? PrivateGet (baseObj ,
V .[[ReferencedName]] ) を返す。
V .[[ReferencedName]] が property
key でなければ、
V .[[ReferencedName]] を
? ToPropertyKey (V .[[ReferencedName]] ) とする。
? baseObj .[[Get]] (V .[[ReferencedName]] , GetThisValue (V ))
を返す。
それ以外の場合、
base を V .[[Base]] とする。
アサート : base は Environment Record
である。
? base .GetBindingValue (V .[[ReferencedName]] , V .[[Strict]] ) を返す(9.1 参照)。
注
3.a
で生成される可能性のあるオブジェクトは、上記の抽象操作および ordinary
object の [[Get]]
内部メソッドの外部からはアクセスできません。実装によっては実際にそのオブジェクトを生成しないこともあります。
6.2.5.6 PutValue ( V , W )
抽象操作 PutValue は、引数 V (Reference
Record または
ECMAScript
言語値 )、W (ECMAScript
言語値 )を受け取り、normal completion
containing な unused または abrupt completion
を返します。呼び出されたとき、次の手順を実行します。
もし V が Reference
Record でなければ、ReferenceError 例外をスローする。
IsUnresolvableReference (V )
が true なら、
もし V .[[Strict]] が
true なら、ReferenceError 例外をスローする。
globalObj を GetGlobalObject () とする。
? Set (globalObj ,
V .[[ReferencedName]] , W ,
false ) を実行する。
unused を返す。
IsPropertyReference (V )
が true なら、
baseObj を ? ToObject (V .[[Base]] ) とする。
IsPrivateReference (V )
が true なら、
? PrivateSet (baseObj ,
V .[[ReferencedName]] ,
W ) を返す。
V .[[ReferencedName]] が property
key でなければ、
V .[[ReferencedName]] を
? ToPropertyKey (V .[[ReferencedName]] ) とする。
succeeded を ? baseObj .[[Set]] (V .[[ReferencedName]] , W , GetThisValue (V ))
とする。
もし succeeded が false かつ V .[[Strict]] が true
なら、TypeError 例外をスローする。
unused を返す。
それ以外の場合、
base を V .[[Base]] とする。
アサート : base は Environment Record
である。
? base .SetMutableBinding (V .[[ReferencedName]] , W , V .[[Strict]] ) を返す(9.1 参照)。
注
3.a
で生成される可能性のあるオブジェクトは、上記の抽象操作および ordinary
object の [[Set]]
内部メソッドの外部からはアクセスできません。実装によっては実際にそのオブジェクトを生成しないこともあります。
6.2.5.7 GetThisValue ( V )
抽象操作 GetThisValue は、引数 V (Reference
Record )を受け取り、ECMAScript 言語値
を返します。呼び出されたとき、次の手順を実行します。
アサート :
IsPropertyReference (V )
が true であること。
IsSuperReference (V )
が true なら V .[[ThisValue]]
を返し、そうでなければ V .[[Base]] を返す。
6.2.5.8 InitializeReferencedBinding ( V , W
)
抽象操作 InitializeReferencedBinding は、引数 V (Reference
Record )、W (ECMAScript
言語値 )を受け取り、normal completion
containing な unused または abrupt completion
を返します。呼び出されたとき、次の手順を実行します。
アサート :
IsUnresolvableReference (V )
が false であること。
base を V .[[Base]] とする。
アサート :
base は Environment Record であること。
? base .InitializeBinding(V .[[ReferencedName]] , W ) を返す。
6.2.5.9 MakePrivateReference ( baseValue ,
privateIdentifier )
抽象操作 MakePrivateReference は、引数 baseValue (ECMAScript
言語値 )、privateIdentifier (文字列)を受け取り、Reference Record
を返します。呼び出されたとき、次の手順を実行します。
privateEnv を 実行中の実行コンテキスト
の PrivateEnvironment とする。
アサート :
privateEnv は null であってはならない。
privateName を ResolvePrivateIdentifier (privateEnv ,
privateIdentifier ) とする。
次の Reference
Record を返す: { [[Base]] :
baseValue , [[ReferencedName]] :
privateName , [[Strict]] :
true , [[ThisValue]] :
empty }.
6.2.6 プロパティ記述子仕様タイプ
Property Descriptor
型は、オブジェクトプロパティ属性の操作および具現化を説明するために用いられます。Property Descriptor は、Record
であり、0個以上のフィールドを持ちます。各フィールド名は属性名であり、その値は 6.1.7.1
で規定された対応する属性値です。この仕様で Property Descriptor レコードのリテラル記述に付与されるスキーマ名は “PropertyDescriptor” です。
Property Descriptor の値は、特定のフィールドの有無によってデータ Property Descriptor またはアクセサ Property Descriptor
に分類されることがあります。[[Value]] または [[Writable]]
という名前のフィールドが存在するものはデータ Property Descriptor です。[[Get]] または [[Set]] という名前のフィールドが存在するものはアクセサ Property Descriptor です。どの Property
Descriptor にも [[Enumerable]] および [[Configurable]] という名前のフィールドを持つことができます。Property Descriptor の値はデータ
Property Descriptor とアクセサ Property Descriptor の両方であってはなりませんが、どちらでもない場合もあります(この場合は汎用 Property
Descriptor です)。完全な Property Descriptor とは、アクセサ Property Descriptor
またはデータ Property Descriptor であり、かつ 表3
に示されたすべての対応フィールドが定義されているものです。
この仕様で Property Descriptor の値を操作するために、以下の 抽象操作 が使用されます:
6.2.6.1 IsAccessorDescriptor ( Desc )
抽象操作 IsAccessorDescriptor は、引数 Desc (Property
Descriptor )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します:
もし Desc が [[Get]]
フィールドを持つなら、true を返す。
もし Desc が [[Set]]
フィールドを持つなら、true を返す。
false を返す。
6.2.6.2 IsDataDescriptor ( Desc )
抽象操作 IsDataDescriptor は、引数 Desc (Property
Descriptor )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します:
もし Desc が [[Value]]
フィールドを持つなら、true を返す。
もし Desc が [[Writable]]
フィールドを持つなら、true を返す。
false を返す。
6.2.6.3 IsGenericDescriptor ( Desc )
抽象操作 IsGenericDescriptor は、引数 Desc (Property
Descriptor )を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します:
IsAccessorDescriptor (Desc )
が true なら、false を返す。
IsDataDescriptor (Desc )
が true なら、false を返す。
true を返す。
6.2.6.4 FromPropertyDescriptor ( Desc )
抽象操作 FromPropertyDescriptor は、引数 Desc (Property
Descriptor または undefined )を受け取り、オブジェクトまたは
undefined を返します。呼び出されたとき、次の手順を実行します:
もし Desc が undefined なら、undefined
を返す。
obj を OrdinaryObjectCreate (%Object.prototype% )
とする。
アサート :
obj は自身のプロパティを持たない拡張可能な ordinary object である。
もし Desc が [[Value]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"value" , Desc .[[Value]] ) を実行する。
もし Desc が [[Writable]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"writable" , Desc .[[Writable]] ) を実行する。
もし Desc が [[Get]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"get" , Desc .[[Get]] )
を実行する。
もし Desc が [[Set]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"set" , Desc .[[Set]] )
を実行する。
もし Desc が [[Enumerable]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"enumerable" , Desc .[[Enumerable]] ) を実行する。
もし Desc が [[Configurable]] フィールドを持つなら:
! CreateDataPropertyOrThrow (obj ,
"configurable" , Desc .[[Configurable]] ) を実行する。
obj を返す。
6.2.6.5 ToPropertyDescriptor ( Obj )
抽象操作 ToPropertyDescriptor は、引数 Obj (ECMAScript
言語値 )を受け取り、normal completion
containing な Property
Descriptor または throw completion
のいずれかを返します。呼び出されたとき、次の手順を実行します:
もし Obj が オブジェクトでない
なら、TypeError 例外をスローする。
desc を新しい Property
Descriptor (初期状態でフィールドなし)とする。
hasEnumerable を ? HasProperty (Obj ,
"enumerable" ) とする。
もし hasEnumerable が true なら:
enumerable を ToBoolean (? Get (Obj ,
"enumerable" )) とする。
desc .[[Enumerable]] に
enumerable を設定する。
hasConfigurable を ? HasProperty (Obj ,
"configurable" ) とする。
もし hasConfigurable が true なら:
configurable を ToBoolean (? Get (Obj ,
"configurable" )) とする。
desc .[[Configurable]] に
configurable を設定する。
hasValue を ? HasProperty (Obj ,
"value" ) とする。
もし hasValue が true なら:
value を ? Get (Obj ,
"value" ) とする。
desc .[[Value]] に value を設定する。
hasWritable を ? HasProperty (Obj ,
"writable" ) とする。
もし hasWritable が true なら:
writable を ToBoolean (? Get (Obj ,
"writable" )) とする。
desc .[[Writable]] に writable
を設定する。
hasGet を ? HasProperty (Obj ,
"get" ) とする。
もし hasGet が true なら:
getter を ? Get (Obj ,
"get" ) とする。
IsCallable (getter )
が false かつ getter が
undefined でなければ、TypeError 例外をスローする。
desc .[[Get]] に getter を設定する。
hasSet を ? HasProperty (Obj ,
"set" ) とする。
もし hasSet が true なら:
setter を ? Get (Obj ,
"set" ) とする。
IsCallable (setter )
が false かつ setter が
undefined でなければ、TypeError 例外をスローする。
desc .[[Set]] に setter を設定する。
もし desc が [[Get]] フィールドまたは [[Set]] フィールドを持つなら:
もし desc が [[Value]] フィールドまたは [[Writable]] フィールドを持つなら、TypeError
例外をスローする。
desc を返す。
6.2.6.6 CompletePropertyDescriptor ( Desc )
抽象操作 CompletePropertyDescriptor は、引数 Desc (Property
Descriptor )を受け取り、unused
を返します。呼び出されたとき、次の手順を実行します:
like を Record { [[Value]] : undefined , [[Writable]] : false , [[Get]] : undefined , [[Set]] : undefined , [[Enumerable]] : false , [[Configurable]] : false } とする。
IsGenericDescriptor (Desc )
が true または IsDataDescriptor (Desc )
が true なら、
もし Desc が [[Value]]
フィールドを持たないなら、Desc .[[Value]] に
like .[[Value]] を設定する。
もし Desc が [[Writable]]
フィールドを持たないなら、Desc .[[Writable]] に
like .[[Writable]] を設定する。
それ以外の場合:
もし Desc が [[Get]]
フィールドを持たないなら、Desc .[[Get]] に
like .[[Get]] を設定する。
もし Desc が [[Set]]
フィールドを持たないなら、Desc .[[Set]] に
like .[[Set]] を設定する。
もし Desc が [[Enumerable]]
フィールドを持たないなら、Desc .[[Enumerable]] に
like .[[Enumerable]] を設定する。
もし Desc が [[Configurable]]
フィールドを持たないなら、Desc .[[Configurable]] に
like .[[Configurable]] を設定する。
unused を返す。
6.2.7 環境レコード仕様タイプ
Environment Record
型は、入れ子になった関数やブロックにおける名前解決の動作を説明するために使用されます。この型およびそれに対する操作は、9.1 で定義されています。
6.2.8 抽象クロージャ仕様タイプ
Abstract Closure
仕様タイプは、アルゴリズムのステップと値の集合をまとめて参照するために用いられます。Abstract Closure
はメタ値であり、closure (arg1 , arg2 ) のような関数適用スタイルで呼び出されます。抽象操作 と同様に、呼び出し時には
Abstract Closure で記述されたアルゴリズムステップが実行されます。
Abstract Closure を生成するアルゴリズムステップでは、「capture」に続いてエイリアスのリストが記載され、その値がキャプチャされます。Abstract Closure
が生成されると、それぞれのエイリアスに対応する値をその時点でキャプチャします。Abstract Closure
を呼び出したときに実行されるアルゴリズムを指定するステップでは、各キャプチャされた値はキャプチャ時に使われたエイリアスで参照されます。
Abstract Closure が Completion Record
を返す場合、その Completion Record は
normal completion または
throw completion
でなければなりません。
Abstract Closure は他のアルゴリズムの一部としてインラインで作成され、次の例のように示されます。
addend を 41 とする。
closure を、パラメータ (x ) を持ち addend
をキャプチャし、呼び出されたときに次のステップを実行する新しい Abstract Closure とする:
x + addend を返す。
val を closure (1) とする。
アサート :
val は 42 である。
6.2.9 データブロック
Data Block
仕様タイプは、個別かつ可変なバイト(8ビット)値のシーケンスを記述するために用いられます。byte
value とは、整数
であり、区間 [0, 255] に含まれるものです。Data Block の値は、各バイトが初期値
0 である固定バイト数で生成されます。
この仕様内では、記法上の便宜のため、Data Block 値の個々のバイトにアクセスするために配列風の構文を使うことができます。この記法は、Data Block 値を 0
基点の整数インデックス付き バイト列として提示します。例えば db が 5 バイトの Data Block
値であれば、db [2] は 3 番目のバイトにアクセスできます。
複数の agent
から同時に参照できるメモリ上のデータブロックは、Shared Data Block
と呼ばれます。Shared Data Block は(等価性判定のための)同一性が アドレスフリー
です:任意のプロセスでマッピングされる仮想アドレスではなく、そのブロックが表すメモリ領域の集合に紐づきます。2つのデータブロックが等しいのは、それらが含む領域の集合が等しい場合のみであり、そうでなければ等しくなく、領域集合の共通部分は空です。最後に、Shared
Data Block と Data Block は区別可能です。
Shared Data Block のセマンティクスは、Shared Data Block イベント
により
メモリーモデル で定義されます。下記の 抽象操作 は Shared Data Block イベント
を導入し、評価セマンティクスと メモリーモデル のイベントセマンティクスのインターフェースとなります。イベントは
候補実行 を形成し、メモリーモデル
がフィルタとして作用します。完全なセマンティクスについては メモリーモデル を参照してください。
Shared Data Block イベント は Record
でモデル化されており、メモリーモデル で定義されています。
この仕様で Data Block 値を操作するために、以下の 抽象操作
が使用されます:
6.2.9.1 CreateByteDataBlock ( size )
抽象操作 CreateByteDataBlock は、引数 size (非負の 整数 )を受け取り、normal completion
containing な Data Block 、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし size > 253 - 1 なら、RangeError
例外をスローする。
db を size バイトからなる新しい Data Block 値とする。そのような
Data
Block を生成できない場合、RangeError 例外をスローする。
db のすべてのバイトを 0 に設定する。
db を返す。
6.2.9.2 CreateSharedByteDataBlock ( size )
抽象操作 CreateSharedByteDataBlock は、引数 size (非負の 整数 )
を受け取り、normal completion
containing な Shared Data Block 、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
db を size バイトからなる新しい Shared Data Block
値とする。そのような Shared Data Block
を生成できない場合、RangeError 例外をスローする。
execution を 周囲のエージェント の Agent
Record の [[CandidateExecution]]
フィールドとする。
eventsRecord を execution .[[EventsRecords]] のうち、[[AgentSignifier]] が AgentSignifier () である
Agent Events Record とする。
zero を « 0 » とする。
db の各インデックス i について、
WriteSharedMemory
{ [[Order]] : init , [[NoTear]] : true , [[Block]] : db , [[ByteIndex]] : i , [[ElementSize]] : 1, [[Payload]] : zero } を
eventsRecord .[[EventList]] に追加する。
db を返す。
6.2.9.3 CopyDataBlockBytes ( toBlock ,
toIndex , fromBlock , fromIndex , count )
抽象操作 CopyDataBlockBytes は、引数 toBlock (Data Block または Shared Data
Block )、toIndex (非負の 整数 )、fromBlock (Data
Block または Shared Data Block )、fromIndex (非負の
整数 )、count (非負の 整数 )を受け取り、unused
を返します。呼び出されたとき、次の手順を実行します:
アサート :
fromBlock と toBlock は異なる値であること。
fromSize を fromBlock のバイト数とする。
アサート :
fromIndex + count ≤ fromSize であること。
toSize を toBlock のバイト数とする。
アサート :
toIndex + count ≤ toSize であること。
count > 0 の間、繰り返す:
もし fromBlock が Shared Data
Block なら、
execution を 周囲のエージェント の
Agent Record の [[CandidateExecution]] フィールドとする。
eventsRecord を execution .[[EventsRecords]] のうち、[[AgentSignifier]] が AgentSignifier ()
である Agent Events
Record とする。
bytes を、唯一の要素が非決定的に選択された byte value である
List
とする。
注:実装において bytes は基盤ハードウェア上の非アトミックな読み取り命令の結果です。非決定性は
メモリーモデル
の意味的要請であり、弱い一貫性を持つハードウェアの観測可能な挙動を記述するためのものです。
readEvent を ReadSharedMemory
{ [[Order]] :
unordered , [[NoTear]] :
true , [[Block]] :
fromBlock , [[ByteIndex]] :
fromIndex , [[ElementSize]] :
1 } とする。
readEvent を eventsRecord .[[EventList]] に追加する。
Chosen Value
Record { [[Event]] :
readEvent , [[ChosenValue]] :
bytes } を execution .[[ChosenValues]] に追加する。
もし toBlock が Shared Data
Block なら、
WriteSharedMemory
{ [[Order]] :
unordered , [[NoTear]] : true ,
[[Block]] : toBlock , [[ByteIndex]] : toIndex ,
[[ElementSize]] : 1, [[Payload]] : bytes }
を eventsRecord .[[EventList]] に追加する。
それ以外の場合:
toBlock [toIndex ] に bytes [0]
を設定する。
それ以外の場合:
アサート : toBlock は
Shared Data Block
でないこと。
toBlock [toIndex ] に
fromBlock [fromIndex ] を設定する。
toIndex を toIndex + 1 に設定する。
fromIndex を fromIndex + 1 に設定する。
count を count - 1 に設定する。
unused を返す。
6.2.10 PrivateElement 仕様タイプ
PrivateElement 型は、プライベートクラスフィールド・メソッド・アクセサの仕様で使用される Record です。Property Descriptor
はプライベート要素には使用されませんが、プライベートフィールドは non-configurable、non-enumerable、writable な データプロパティ
と同様に動作し、プライベートメソッドは non-configurable、non-enumerable、non-writable な データプロパティ
と同様に、プライベートアクセサは non-configurable、non-enumerable な アクセサプロパティ と同様に動作します。
PrivateElement 型の値は、Record 値であり、そのフィールドは
表9 で定義されています。これらの値は PrivateElement と呼ばれます。
表9: PrivateElement
のフィールド
フィールド名
そのフィールドが存在する [[Kind]] フィールドの値
値
意味
[[Key]]
全て
Private Name
フィールド、メソッド、またはアクセサの名前。
[[Kind]]
全て
field , method , または
accessor
要素の種類。
[[Value]]
field および method
ECMAScript 言語値
フィールドの値。
[[Get]]
accessor
関数オブジェクト または
undefined
プライベートアクセサの getter。
[[Set]]
accessor
関数オブジェクト または
undefined
プライベートアクセサの setter。
6.2.11 ClassFieldDefinition レコード仕様タイプ
ClassFieldDefinition 型は、クラスフィールドの仕様で使用される Record です。
ClassFieldDefinition 型の値は Record
値であり、そのフィールドは 表10 で定義されています。これらの値は ClassFieldDefinition Record
と呼ばれます。
表10: ClassFieldDefinition
Record のフィールド
フィールド名
値
意味
[[Name]]
Private Name 、文字列、または
シンボル
フィールドの名前。
[[Initializer]]
ECMAScript 関数オブジェクト または
empty
フィールドの初期化子(あれば)。
6.2.12 プライベート名
Private Name
仕様タイプは、プライベートクラス要素(フィールド、メソッド、アクセサ)のキーを表すグローバルに一意な値(たとえ他の Private Name
と区別がつかなくても、必ず異なる値)を記述するために用いられます。各 Private Name には、文字列 値である不変の [[Description]] が関連付けられています。Private Name は、PrivateFieldAdd または PrivateMethodOrAccessorAdd を使って任意の
ECMAScript オブジェクトにインストールでき、その後 PrivateGet および PrivateSet を使って読み書きできます。
6.2.13 ClassStaticBlockDefinition レコード仕様タイプ
ClassStaticBlockDefinition
Record は、クラスの static 初期化ブロックの実行可能なコードをカプセル化するために用いられる Record 値です。
ClassStaticBlockDefinition Record は、表11 に示すフィールドを持ちます。
表11: ClassStaticBlockDefinition
Record のフィールド
フィールド名
値
意味
[[BodyFunction]]
ECMAScript 関数オブジェクト
クラスの static 初期化時に呼び出される 関数オブジェクト 。
7 抽象操作
これらの操作は ECMAScript 言語の一部ではなく、ECMAScript 言語のセマンティクス仕様を補助するためだけにここで定義されています。他にも、より専門的な抽象操作 が本仕様全体で定義されています。
7.1 型変換
ECMAScript 言語は必要に応じて暗黙的に自動型変換を行います。特定の構文のセマンティクスを明確にするために、一連の変換抽象操作 を定義することが有用です。これらの変換抽象操作 は多態的であり、任意のECMAScript
言語型 の値を受け入れることができます。ただし、これらの操作で他の仕様タイプは使用されません。
BigInt 型 は ECMAScript
言語において自動変換されることはありません。開発者は他の型から変換したい場合は明示的に BigInt を呼び出す必要があります。
7.1.1 ToPrimitive ( input [ , preferredType ]
)
抽象操作 ToPrimitive は、引数 input (ECMAScript
言語値 )と、オプションの引数 preferredType (string または
number )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。この操作は input 引数を非Object
型 に変換します。オブジェクトが複数のプリミティブ型に変換可能な場合、オプションのヒント preferredType
を使ってその型を優先することがあります。呼び出されたとき、次の手順を実行します:
もし input がオブジェクト なら、
exoticToPrim を ? GetMethod (input , %Symbol.toPrimitive% ) とする。
もし exoticToPrim が undefined でなければ、
もし preferredType が与えられていなければ、
hint を "default" とする。
そうでなく、preferredType が string なら、
hint を "string" とする。
それ以外の場合、
アサート :
preferredType は number である。
hint を "number" とする。
result を ? Call (exoticToPrim ,
input , « hint » ) とする。
もし result がオブジェクトでなければ
result を返す。
TypeError 例外をスローする。
もし preferredType が与えられていなければ、preferredType を
number とする。
? OrdinaryToPrimitive (input ,
preferredType ) を返す。
input を返す。
注
ToPrimitive がヒントなしで呼ばれた場合、一般的にはヒントが number
であるかのように振る舞います。ただし、オブジェクトが %Symbol.toPrimitive%
メソッドを定義することでこの振る舞いを上書きできます。本仕様で定義されているオブジェクトの中でこのデフォルトの ToPrimitive の振る舞いを上書きするのは
Date(21.4.4.45 )と
Symbol オブジェクト(20.4.3.5 )のみです。Date
はヒントが未指定の場合、string であるかのように振る舞います。
7.1.1.1 OrdinaryToPrimitive ( O , hint )
抽象操作 OrdinaryToPrimitive は、引数 O (オブジェクト)と
hint (string または
number )を受け取り、normal completion
containing な ECMAScript 言語値
または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし hint が string なら、
methodNames を « "toString" ,
"valueOf" » とする。
それ以外の場合、
methodNames を « "valueOf" ,
"toString" » とする。
methodNames の各要素 name について、
method を ? Get (O ,
name ) とする。
もし IsCallable (method )
が true なら、
result を ? Call (method ,
O ) とする。
もし result がオブジェクトでなければ
result を返す。
TypeError 例外をスローする。
7.1.2 ToBoolean ( argument )
抽象操作 ToBoolean は、引数 argument (ECMAScript
言語値 )を受け取り、Boolean を返します。argument を Boolean
型の値に変換します。呼び出されたとき、次の手順を実行します:
もし argument がBoolean
なら、argument を返す。
もし argument が
undefined 、null 、+0 𝔽 、-0 𝔽 、NaN 、0 ℤ 、または空文字列のいずれかなら、false
を返す。
注:このステップは B.3.6.1 で置き換えられます。
true を返す。
7.1.3 ToNumeric ( value )
抽象操作 ToNumeric は、引数 value (ECMAScript
言語値 )を受け取り、normal completion
containing な Number または BigInt、あるいは throw completion
を返します。value を Number または BigInt に変換して返します。呼び出されたとき、次の手順を実行します:
primValue を ? ToPrimitive (value ,
number ) とする。
もし primValue がBigInt
なら、primValue を返す。
? ToNumber (primValue ) を返す。
7.1.4 ToNumber ( argument )
抽象操作 ToNumber は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な Number、または throw completion
を返します。argument を Number 型の値に変換します。呼び出されたとき、次の手順を実行します:
もし argument がNumber
なら、argument を返す。
もし argument が Symbol または BigInt なら、TypeError 例外をスローする。
もし argument が undefined なら、NaN を返す。
もし argument が null または false
なら、+0 𝔽 を返す。
もし argument が true なら、1 𝔽
を返す。
もし argument が文字列 なら、StringToNumber (argument )
を返す。
アサート :
argument はオブジェクト である。
primValue を ? ToPrimitive (argument ,
number ) とする。
アサート :
primValue はオブジェクトでない こと。
? ToNumber (primValue ) を返す。
7.1.4.1 文字列型に適用される ToNumber
抽象操作 StringToNumber
は、次の文法を用いて文字列値を数値値へ変換する方法を規定します。
構文
StringNumericLiteral
:::
StrWhiteSpace opt
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrWhiteSpace :::
StrWhiteSpaceChar
StrWhiteSpace opt
StrWhiteSpaceChar
:::
WhiteSpace
LineTerminator
StrNumericLiteral
:::
StrDecimalLiteral
NonDecimalIntegerLiteral [~Sep]
StrDecimalLiteral
:::
StrUnsignedDecimalLiteral
+
StrUnsignedDecimalLiteral
-
StrUnsignedDecimalLiteral
StrUnsignedDecimalLiteral
:::
Infinity
DecimalDigits [~Sep]
.
DecimalDigits [~Sep] opt
ExponentPart [~Sep] opt
.
DecimalDigits [~Sep]
ExponentPart [~Sep] opt
DecimalDigits [~Sep]
ExponentPart [~Sep] opt
上記で明示的に定義されていない全ての文法記号は、数値リテラルの字句文法(12.9.3 )で使われている定義を持ちます。
注
StringNumericLiteral の構文と
NumericLiteral
の構文にはいくつかの違いがあることに注意してください:
7.1.4.1.1 StringToNumber ( str )
抽象操作 StringToNumber は、引数 str (文字列)を受け取り、数値を返します。呼び出されたとき、次の手順を実行します:
literal を ParseText (str , StringNumericLiteral )
とする。
もし literal が List
のエラーであれば、NaN を返す。
literal の StringNumericValue
を返す。
7.1.4.1.2 実行時セマンティクス: StringNumericValue
構文指示操作
StringNumericValue は引数を取らず、数値を返します。
注
StringNumericLiteral
から数値値への変換は、NumericValue (NumericLiteral
の値、12.9.3
参照)の決定と全体的に似ていますが、詳細にはいくつか差異があります。
以下の生成規則に対し分割的に定義されます:
StringNumericLiteral
::: StrWhiteSpace opt
+0 𝔽 を返す。
StringNumericLiteral
:::
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrNumericLiteral の
StringNumericValue
を返す。
StrNumericLiteral
::: NonDecimalIntegerLiteral
NonDecimalIntegerLiteral
の MV を 𝔽 で返す。
StrDecimalLiteral
:::
-
StrUnsignedDecimalLiteral
a を StrUnsignedDecimalLiteral
の StringNumericValue
とする。
もし a が +0 𝔽 なら
-0 𝔽 を返す。
-a を返す。
StrUnsignedDecimalLiteral
::: Infinity
+∞ 𝔽 を返す。
StrUnsignedDecimalLiteral
:::
DecimalDigits
.
DecimalDigits opt
ExponentPart opt
最初の DecimalDigits の MV を
a とする。
2番目の DecimalDigits が存在する場合、
2番目の DecimalDigits の MV を
b とする。
2番目の DecimalDigits の符号位置数を
n とする。
それ以外の場合、
b を 0 とする。
n を 0 とする。
ExponentPart
が存在する場合、e を ExponentPart の MV とし、それ以外の場合
e を 0 とする。
RoundMVResult ((a +
(b × 10-n )) × 10e ) を返す。
StrUnsignedDecimalLiteral
:::
.
DecimalDigits
ExponentPart opt
DecimalDigits
の MV を b とする。
ExponentPart
が存在する場合、e を ExponentPart の MV とし、それ以外の場合
e を 0 とする。
DecimalDigits
の符号位置数を n とする。
RoundMVResult (b ×
10e - n ) を返す。
StrUnsignedDecimalLiteral
:::
DecimalDigits
ExponentPart opt
DecimalDigits
の MV を a とする。
ExponentPart
が存在する場合、e を ExponentPart の MV とし、それ以外の場合
e を 0 とする。
RoundMVResult (a ×
10e ) を返す。
7.1.4.1.3 RoundMVResult ( n )
抽象操作 RoundMVResult は、引数 n (数学値 )を受け取り、数値を返します。これは
n を 実装依存
の方法で数値に変換します。この抽象操作においては、ある桁が有効桁であるとは、その桁が 0 でないか、左か右のいずれかに 0 でない桁が存在する場合を意味します。また、「ある
数学値 の表現が表す 数学値 」とは、「数学値
の10進表現」の逆であるとみなします。呼び出されたとき、次の手順を実行します:
n の10進表現が20桁以下の有効桁を持つ場合、𝔽 (n ) を返す。
option1 を、n の10進表現の21桁目以降の有効桁をすべて0に置き換えた結果が表す 数学値 とする。
option2 を、n
の10進表現の21桁目以降の有効桁をすべて0に置き換えた後、21桁目を切り上げ(必要に応じて繰り上げ)た結果が表す 数学値 とする。
chosen を、実装依存 に option1
または option2 のいずれかとする。
𝔽 (chosen ) を返す。
7.1.5 ToIntegerOrInfinity ( argument )
抽象操作 ToIntegerOrInfinity は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 、+∞、または -∞、あるいは throw completion
を返します。これは argument を、その Number 値の小数部分を切り捨てた整数、または Number 値が無限大の場合 +∞ あるいは -∞
に変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が
NaN 、+0 𝔽 、-0 𝔽
のいずれかなら、0 を返す。
もし number が +∞ 𝔽 なら、+∞ を返す。
もし number が -∞ 𝔽 なら、-∞ を返す。
truncate (ℝ (number )) を返す。
注
𝔽 (ToIntegerOrInfinity(
x )) は、任意の
x
に対して
-0 𝔽 を返すことはありません。小数部分の切り捨ては
x を
数学値 に変換した後に行われます。
7.1.6 ToInt32 ( argument )
抽象操作 ToInt32 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
𝔽 (-231 ) から 𝔽 (231 - 1)
のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int32bit を int modulo 232 とする。
もし int32bit ≥ 231 なら、𝔽 (int32bit - 232 ) を返し、そうでなければ
𝔽 (int32bit )
を返す。
注
上記 ToInt32 の定義により:
ToInt32 抽象操作は冪等性を持ちます:その結果に再度適用しても値は変わりません。
ToInt32(ToUint32 (x )) は、任意の
x に対し ToInt32(x )
と同じ値を返します。(この性質を保つために、+∞ 𝔽 と
-∞ 𝔽 は +0 𝔽 に変換されます。)
ToInt32 は -0 𝔽 を +0 𝔽
にマッピングします。
7.1.7 ToUint32 ( argument )
抽象操作 ToUint32 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
+0 𝔽 から 𝔽 (232 - 1) のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int32bit を int modulo 232 とする。
𝔽 (int32bit ) を返す。
注
上記 ToUint32 の定義により:
5 は ToUint32 と ToInt32
の唯一の違いです。
ToUint32 抽象操作は冪等性を持ちます:その結果に再度適用しても値は変わりません。
ToUint32(ToInt32 (x )) は、任意の x
に対し ToUint32(x ) と同じ値を返します。(この性質を保つために、+∞ 𝔽
と -∞ 𝔽 は +0 𝔽 に変換されます。)
ToUint32 は -0 𝔽 を +0 𝔽
にマッピングします。
7.1.8 ToInt16 ( argument )
抽象操作 ToInt16 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
𝔽 (-215 ) から 𝔽 (215 - 1)
のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int16bit を int modulo 216 とする。
もし int16bit ≥ 215 なら、𝔽 (int16bit - 216 ) を返し、そうでなければ
𝔽 (int16bit )
を返す。
7.1.9 ToUint16 ( argument )
抽象操作 ToUint16 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
+0 𝔽 から 𝔽 (216 - 1) のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int16bit を int modulo 216 とする。
𝔽 (int16bit )
を返す。
注
上記 ToUint16 の定義により:
4 で 216 を使うことが ToUint32 と
ToUint16 の唯一の違いです。
ToUint16 は -0 𝔽 を +0 𝔽
にマッピングします。
7.1.10 ToInt8 ( argument )
抽象操作 ToInt8 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
-128 𝔽 から 127 𝔽
のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int8bit を int modulo 28 とする。
もし int8bit ≥ 27 なら、𝔽 (int8bit - 28 ) を返し、そうでなければ
𝔽 (int8bit )
を返す。
7.1.11 ToUint8 ( argument )
抽象操作 ToUint8 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を 整数 Number のうち、区間
+0 𝔽 から 255 𝔽
のいずれかに変換します。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が 有限 でない、または number が
+0 𝔽 もしくは -0 𝔽
であるなら、+0 𝔽 を返す。
int を truncate (ℝ (number )) とする。
int8bit を int modulo 28 とする。
𝔽 (int8bit )
を返す。
7.1.12 ToUint8Clamp ( argument )
抽象操作 ToUint8Clamp は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な 整数 Number 、または throw completion
を返します。これは argument を整数 Number のうち、区間
+0 𝔽 から 255 𝔽
に丸めてクランプします。呼び出されたとき、次の手順を実行します:
number を ? ToNumber (argument ) とする。
もし number が NaN なら、+0 𝔽 を返す。
mv を number の拡張数学値 とする。
clamped を clamping mv を 0 から 255
の間でクランプした結果とする。
f を floor (clamped ) とする。
もし clamped < f + 0.5 なら、𝔽 (f ) を返す。
もし clamped > f + 0.5 なら、𝔽 (f + 1) を返す。
もし f が偶数なら、𝔽 (f ) を返し、そうでなければ 𝔽 (f + 1) を返す。
注
他のほとんどの ECMAScript 整数 変換操作とは異なり、ToUint8Clamp
は非整数値を切り捨てるのではなく丸めます。また、Math.round
の「四捨五入」タイブレークとは異なり、「最近接偶数への丸め(round half to even)」を使用します。
7.1.13 ToBigInt ( argument )
抽象操作 ToBigInt は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な BigInt、または throw completion
を返します。これは argument を BigInt 値に変換し、Number からの暗黙的な変換が必要な場合は例外を投げます。呼び出されたとき、次の手順を実行します:
prim を ? ToPrimitive (argument ,
number ) とする。
prim に対応する値を 表12 から返す。
表12: BigInt 変換
引数の型
結果
Undefined
TypeError 例外を投げる。
Null
TypeError 例外を投げる。
Boolean
prim が true なら 1n、prim
が false なら 0n を返す。
BigInt
prim を返す。
Number
TypeError 例外を投げる。
String
n を StringToBigInt (prim )
とする。
もし n が undefined
なら、SyntaxError 例外を投げる。
n を返す。
Symbol
TypeError 例外を投げる。
7.1.14 StringToBigInt ( str )
抽象操作 StringToBigInt は、引数 str (文字列)を受け取り、BigInt または undefined
を返します。呼び出されたとき、次の手順を実行します:
literal を ParseText (str , StringIntegerLiteral ) とする。
もし literal が List
のエラーであれば、undefined を返す。
mv を literal の MV とする。
アサート :
mv は 整数 である。
ℤ (mv ) を返す。
7.1.14.1 StringIntegerLiteral 文法
StringToBigInt は次の文法を使用します。
構文
StringIntegerLiteral
:::
StrWhiteSpace opt
StrWhiteSpace opt
StrIntegerLiteral
StrWhiteSpace opt
StrIntegerLiteral
:::
SignedInteger [~Sep]
NonDecimalIntegerLiteral [~Sep]
7.1.14.2 実行時セマンティクス: MV
7.1.15 ToBigInt64 ( argument )
抽象操作 ToBigInt64 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な BigInt、または throw completion
を返します。これは argument を 区間 ℤ (-263 ) から ℤ (263 - 1) の 264 個の BigInt
値のいずれかに変換します。呼び出されたとき、次の手順を実行します:
n を ? ToBigInt (argument ) とする。
int64bit を ℝ (n ) modulo 264 とする。
もし int64bit ≥ 263 なら、ℤ (int64bit - 264 ) を返し、そうでなければ
ℤ (int64bit )
を返す。
7.1.16 ToBigUint64 ( argument )
抽象操作 ToBigUint64 は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な BigInt、または throw completion
を返します。これは argument を 区間 0 ℤ から
ℤ (264 - 1) の
264 個の BigInt 値のいずれかに変換します。呼び出されたとき、次の手順を実行します:
n を ? ToBigInt (argument ) とする。
int64bit を ℝ (n ) modulo 264 とする。
ℤ (int64bit )
を返す。
7.1.17 ToString ( argument )
抽象操作 ToString は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な文字列、または throw completion
を返します。これは argument を String 型の値に変換します。呼び出されたとき、次の手順を実行します:
もし argument が文字列 なら、argument
を返す。
もし argument がシンボル なら、TypeError
例外を投げる。
もし argument が undefined なら、"undefined"
を返す。
もし argument が null なら、"null" を返す。
もし argument が true なら、"true" を返す。
もし argument が false なら、"false" を返す。
もし argument が数値 なら、Number::toString (argument ,
10) を返す。
もし argument がBigInt なら、BigInt::toString (argument ,
10) を返す。
アサート :
argument はオブジェクト である。
primValue を ? ToPrimitive (argument ,
string ) とする。
アサート :
primValue はオブジェクトでない こと。
? ToString (primValue ) を返す。
7.1.18 ToObject ( argument )
抽象操作 ToObject は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing なオブジェクト、または throw completion
を返します。これは argument を 表13 に従って Object 型の値に変換します:
表13: ToObject 変換
引数の型
結果
Undefined
TypeError 例外を投げる。
Null
TypeError 例外を投げる。
Boolean
[[BooleanData]] 内部スロットが argument
に設定された新しい Boolean オブジェクトを返す。Boolean オブジェクトの説明は 20.3 を参照。
Number
[[NumberData]] 内部スロットが argument
に設定された新しい Number オブジェクトを返す。Number オブジェクトの説明は 21.1 を参照。
String
[[StringData]] 内部スロットが argument
に設定された新しい String オブジェクトを返す。String オブジェクトの説明は 22.1 を参照。
Symbol
[[SymbolData]] 内部スロットが argument
に設定された新しい Symbol オブジェクトを返す。Symbol オブジェクトの説明は 20.4 を参照。
BigInt
[[BigIntData]] 内部スロットが argument
に設定された新しい BigInt オブジェクトを返す。BigInt オブジェクトの説明は 21.2 を参照。
Object
argument を返す。
7.1.19 ToPropertyKey ( argument )
抽象操作 ToPropertyKey は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な プロパティキー 、または throw completion
を返します。これは argument を プロパティキー として使用できる値に変換します。呼び出されたとき、次の手順を実行します:
key を ? ToPrimitive (argument ,
string ) とする。
もし key がシンボル なら、
key を返す。
! ToString (key ) を返す。
7.1.20 ToLength ( argument )
抽象操作 ToLength は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な非負の 整数 Number 、または throw completion
を返します。これは argument を 整数 Number へクランプし切り捨てて、配列様オブジェクト
の長さとして使える値にします。呼び出されたとき、次の手順を実行します:
len を ? ToIntegerOrInfinity (argument ) とする。
もし len ≤ 0 なら、+0 𝔽 を返す。
𝔽 (min (len ,
253 - 1)) を返す。
7.1.21 CanonicalNumericIndexString ( argument )
抽象操作 CanonicalNumericIndexString は、引数 argument (文字列)を受け取り、数値または
undefined を返します。argument が "-0" または、ある数値
n について ToString (n ) に完全一致する場合は、その数値 n
を返します。それ以外は undefined を返します。呼び出されたとき、次の手順を実行します:
もし argument が "-0" なら、-0 𝔽
を返す。
n を ! ToNumber (argument ) とする。
もし ! ToString (n ) が argument
と一致するなら、n を返す。
undefined を返す。
canonical numeric string
とは、CanonicalNumericIndexString 抽象操作が undefined を返さない任意の文字列です。
7.1.22 ToIndex ( value )
抽象操作 ToIndex は、引数 value (ECMAScript
言語値 )を受け取り、normal completion
containing な非負の 整数 、または throw completion
を返します。これは value を 整数 に変換し、それが非負かつ 整数インデックス
に対応していればその整数を返します。そうでなければ例外を投げます。呼び出されたとき、次の手順を実行します:
integer を ? ToIntegerOrInfinity (value ) とする。
もし integer が 区間 0 から 253 - 1
に含まれていなければ、RangeError 例外を投げる。
integer を返す。
7.2 テストおよび比較操作
7.2.1 RequireObjectCoercible ( argument )
抽象操作 RequireObjectCoercible は、引数 argument (ECMAScript 言語値 )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。argument を ToObject でオブジェクトに変換できない値の場合はエラーを投げます。表14 で定義されています:
表14: RequireObjectCoercible の結果
引数の型
結果
Undefined
TypeError 例外を投げる。
Null
TypeError 例外を投げる。
Boolean
argument を返す。
Number
argument を返す。
String
argument を返す。
Symbol
argument を返す。
BigInt
argument を返す。
Object
argument を返す。
7.2.2 IsArray ( argument )
抽象操作 IsArray は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な Boolean、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし argument がオブジェクトでない 場合、false を返す。
もし argument が 配列エキゾチックオブジェクト なら
true を返す。
もし argument が Proxy エキゾチックオブジェクト なら、
? ValidateNonRevokedProxy (argument )
を行う。
proxyTarget を argument .[[ProxyTarget]] とする。
? IsArray (proxyTarget ) を返す。
false を返す。
7.2.3 IsCallable ( argument )
抽象操作 IsCallable は、引数 argument (ECMAScript
言語値 )を受け取り、Boolean を返します。argument が [[Call]] 内部メソッドを持つ呼び出し可能な関数かを判定します。呼び出されたとき、次の手順を実行します:
もし argument がオブジェクトでない 場合、false を返す。
もし argument が [[Call]] 内部メソッドを持てば
true を返す。
false を返す。
7.2.4 IsConstructor ( argument )
抽象操作 IsConstructor は、引数 argument (ECMAScript
言語値 )を受け取り、Boolean を返します。argument が 関数オブジェクト で
[[Construct]] 内部メソッドを持つかどうかを判定します。呼び出されたとき、次の手順を実行します:
もし argument がオブジェクトでない 場合、false を返す。
もし argument が [[Construct]] 内部メソッドを持てば
true を返す。
false を返す。
7.2.5 IsExtensible ( O )
抽象操作 IsExtensible は、引数 O (オブジェクト)を受け取り、normal completion
containing な Boolean、または throw completion
を返します。これは O にプロパティを追加できるかを判定するために使われます。呼び出されたとき、次の手順を実行します:
? O .[[IsExtensible]] () を返す。
7.2.6 IsRegExp ( argument )
抽象操作 IsRegExp は、引数 argument (ECMAScript
言語値 )を受け取り、normal completion
containing な Boolean、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし argument がオブジェクトでない 場合、false を返す。
matcher を ? Get (argument ,
%Symbol.match% ) とする。
もし matcher が undefined でなければ、ToBoolean (matcher )
を返す。
もし argument が [[RegExpMatcher]]
内部スロットを持てば、true を返す。
false を返す。
7.2.7 静的セマンティクス: IsStringWellFormedUnicode (
string )
抽象操作 IsStringWellFormedUnicode は、引数 string (文字列)を受け取り、Boolean を返します。string を
6.1.4 で説明される UTF-16
エンコード符号点列として解釈し、well
formed な UTF-16 シーケンスかどうかを判定します。呼び出されたとき、次の手順を実行します:
len を string の長さとする。
k を 0 とする。
繰り返し、k < len の間:
cp を CodePointAt (string ,
k ) とする。
もし cp .[[IsUnpairedSurrogate]] が
true なら、false を返す。
k を k + cp .[[CodeUnitCount]] に設定する。
true を返す。
7.2.8 SameType ( x , y )
抽象操作 SameType は、引数 x (ECMAScript 言語値 )と
y (ECMAScript 言語値 )を受け取り、Boolean
を返します。2つの引数が同じ型かどうかを判定します。呼び出されたとき、次の手順を実行します:
もし x が undefined かつ y も
undefined なら true を返す。
もし x が null かつ y も null なら
true を返す。
もし x がBoolean かつ
y もBoolean なら
true を返す。
もし x がNumber かつ
y もNumber なら
true を返す。
もし x がBigInt かつ
y もBigInt なら
true を返す。
もし x がシンボル かつ
y もシンボル なら
true を返す。
もし x が文字列 かつ
y も文字列 なら
true を返す。
もし x がオブジェクト かつ y もオブジェクト なら true を返す。
false を返す。
7.2.9 SameValue ( x , y )
抽象操作 SameValue は、引数 x (ECMAScript 言語値 )および
y (ECMAScript 言語値 )を受け取り、Boolean
を返します。これは2つの引数が同じ値かどうかを判定します。呼び出されたとき、次の手順を実行します:
もし SameType (x , y ) が
false なら、false を返す。
もし x がNumber なら、
Number::sameValue (x ,
y ) を返す。
SameValueNonNumber (x ,
y ) を返す。
注
このアルゴリズムは IsStrictlyEqual アルゴリズムと異なり、全ての
NaN を等価とみなし、+0 𝔽 と
-0 𝔽 を区別します。
7.2.10 SameValueZero ( x , y )
抽象操作 SameValueZero は、引数 x (ECMAScript 言語値 )および
y (ECMAScript 言語値 )を受け取り、Boolean
を返します。これは2つの引数が同じ値かどうか(+0 𝔽 と -0 𝔽
の違いを無視)を判定します。呼び出されたとき、次の手順を実行します:
もし SameType (x , y ) が
false なら、false を返す。
もし x がNumber なら、
Number::sameValueZero (x ,
y ) を返す。
SameValueNonNumber (x ,
y ) を返す。
注
SameValueZero は SameValue
と異なり、+0 𝔽 と -0 𝔽 を等価とみなします。
7.2.11 SameValueNonNumber ( x , y )
抽象操作 SameValueNonNumber は、引数 x (ECMAScript 言語値 ただし
Number ではない)および y (ECMAScript 言語値 ただし Number
ではない)を受け取り、Boolean を返します。呼び出されたとき、次の手順を実行します:
アサート :
SameType (x , y ) は
true である。
もし x が undefined または null
なら、true を返す。
もし x がBigInt なら、
BigInt::equal (x ,
y ) を返す。
もし x が文字列 なら、
もし x と y の長さが等しく、かつ同じ位置のコード単位が全て一致するなら
true を返し、そうでなければ false を返す。
もし x がBoolean なら、
もし x と y がともに true かともに
false なら true を返し、そうでなければ
false を返す。
注:その他の ECMAScript 言語値
は同一性(identity)で比較されます。
もし x が y であれば true 、そうでなければ
false を返す。
注1
本アルゴリズムでは説明の都合上、実際には分離しなくてもよい場合でも一部のケースを分離して取り扱っています。
注2
「
x が
y である」の詳細は
5.2.7 を参照してください。
7.2.12 IsLessThan ( x , y , LeftFirst
)
抽象操作 IsLessThan は、引数 x (ECMAScript
言語値 )、y (ECMAScript
言語値 )、LeftFirst (Boolean)を受け取り、normal completion
containing な Boolean または undefined 、あるいは throw completion
を返します。これは x < y
の比較の意味を提供し、true 、false 、または(少なくとも一方が NaN
の場合)undefined を返します。LeftFirst フラグは x および y
への副作用の順序を制御するために使われます。これは ECMAScript が式の評価を左から右に行うことを規定しているため、必要です。LeftFirst が
true なら x は y より左の式、false なら逆に
y の方を先に評価します。呼び出されたとき、次の手順を実行します:
もし LeftFirst が true なら、
px を ? ToPrimitive (x ,
number ) とする。
py を ? ToPrimitive (y ,
number ) とする。
それ以外の場合、
注:評価順を逆にすることで左から右の評価を保証する必要がある。
py を ? ToPrimitive (y ,
number ) とする。
px を ? ToPrimitive (x ,
number ) とする。
もし px が文字列 かつ
py も文字列 なら、
lx を px の長さとする。
ly を py の長さとする。
0 ≤ i < min (lx , ly ) である
整数
i について昇順で、
cx を px のインデックス i のコード単位の数値とする。
cy を py のインデックス i のコード単位の数値とする。
もし cx < cy なら true を返す。
もし cx > cy なら false を返す。
もし lx < ly なら true を返し、そうでなければ
false を返す。
それ以外の場合、
もし px がBigInt
かつ py が文字列 なら、
ny を StringToBigInt (py )
とする。
もし ny が undefined なら
undefined を返す。
BigInt::lessThan (px ,
ny ) を返す。
もし px が文字列 かつ
py がBigInt
なら、
nx を StringToBigInt (px )
とする。
もし nx が undefined なら
undefined を返す。
BigInt::lessThan (nx ,
py ) を返す。
注:px と py はプリミティブ値なので評価順は重要でない。
nx を ? ToNumeric (px ) とする。
ny を ? ToNumeric (py ) とする。
もし SameType (nx ,
ny ) が true なら、
もし nx がNumber
なら、
Number::lessThan (nx ,
ny ) を返す。
それ以外の場合、
アサート : nx
はBigInt である。
BigInt::lessThan (nx ,
ny ) を返す。
アサート :
nx はBigInt で、ny
はNumber 、または
nx はNumber
で ny はBigInt 。
もし nx または ny が NaN なら
undefined を返す。
もし nx が -∞ 𝔽 または ny が
+∞ 𝔽 なら true を返す。
もし nx が +∞ 𝔽 または ny が
-∞ 𝔽 なら false を返す。
もし ℝ (nx ) < ℝ (ny ) なら
true を返し、そうでなければ false を返す。
注1
ステップ 3 は、加算演算子 +
を扱うアルゴリズム(13.15.3 )のステップ
1.c
と異なり、論理積(and)を使います(そちらは論理和 or)。
注2
文字列の比較は UTF-16 コード単位列に対する単純な辞書順比較を用います。Unicode
仕様で定義されるより複雑で意味論的な文字・文字列の等価性や照合順序は考慮されません。そのため、Unicode
標準で正規等価な値であっても正規化形式が異なる場合は等価判定されないことがあります。また、コード単位 による辞書順は、サロゲートペア を含む文字列ではコードポイント による順序付けとは異なります。
7.2.13 IsLooselyEqual ( x , y )
抽象操作 IsLooselyEqual は、引数 x (ECMAScript 言語値 )および
y (ECMAScript 言語値 )を受け取り、normal completion
containing な Boolean、または throw completion
を返します。これは == 演算子の意味を与えます。呼び出されたとき、次の手順を実行します:
もし SameType (x , y ) が
true なら、
IsStrictlyEqual (x ,
y ) を返す。
もし x が null かつ y が undefined
なら true を返す。
もし x が undefined かつ y が null
なら true を返す。
注:このステップは B.3.6.2 で置き換えられます。
もし x がNumber かつ
y が文字列 なら、! IsLooselyEqual (x ,
! ToNumber (y )) を返す。
もし x が文字列 かつ
y がNumber なら、! IsLooselyEqual (! ToNumber (x ), y ) を返す。
もし x がBigInt かつ
y が文字列 なら、
n を StringToBigInt (y )
とする。
もし n が undefined なら false を返す。
! IsLooselyEqual (x ,
n ) を返す。
もし x が文字列 かつ
y がBigInt なら、! IsLooselyEqual (y ,
x ) を返す。
もし x がBoolean
なら、! IsLooselyEqual (! ToNumber (x ), y ) を返す。
もし y がBoolean
なら、! IsLooselyEqual (x ,
! ToNumber (y )) を返す。
もし x が 文字列、数値、BigInt、またはシンボルのいずれかで y がオブジェクト なら、! IsLooselyEqual (x ,
? ToPrimitive (y )) を返す。
もし x がオブジェクト かつ y が
文字列、数値、BigInt、またはシンボルのいずれかなら、! IsLooselyEqual (? ToPrimitive (x ), y ) を返す。
もし x がBigInt かつ
y がNumber 、または
x がNumber かつ
y がBigInt なら、
もし x が有限 でないか、または y が有限 でなければ
false を返す。
もし ℝ (x )
= ℝ (y )
なら true を返し、そうでなければ false を返す。
false を返す。
7.2.14 IsStrictlyEqual ( x , y )
抽象操作 IsStrictlyEqual は、引数 x (ECMAScript 言語値 )および
y (ECMAScript 言語値 )を受け取り、Boolean
を返します。これは === 演算子の意味を与えます。呼び出されたとき、次の手順を実行します:
もし SameType (x , y ) が
false なら、false を返す。
もし x がNumber なら、
Number::equal (x ,
y ) を返す。
SameValueNonNumber (x ,
y ) を返す。
注
このアルゴリズムは SameValue アルゴリズムと、符号付き0やNaNの扱いが異なります。
7.3 オブジェクトに対する操作
7.3.1 MakeBasicObject ( internalSlotsList )
抽象操作 MakeBasicObject は、引数 internalSlotsList (内部スロット名のリスト )を受け取り、オブジェクトを返します。これはアルゴリズム的に生成される全ての
ECMAScript オブジェクト、すなわち 通常オブジェクト や エキゾチックオブジェクト
を含む全オブジェクトの元となります。全てのオブジェクト生成で共通となる手順を切り出し、オブジェクト生成を一元化します。呼び出されたとき、次の手順を実行します:
internalSlotsList を リスト連結 で internalSlotsList と
« [[PrivateElements]] » の連結に設定する。
internalSlotsList の各名前に対応する内部スロットを持つ新しいオブジェクト obj を生成する。
注:オブジェクトの内部メソッドと内部スロット
で説明されているように、これらの内部スロットの初期値は特に指定がない限り undefined である。
obj .[[PrivateElements]] を新しい空の リスト に設定する。
obj の本質的な内部メソッドを、通常オブジェクト の 10.1
で規定されるデフォルトの定義に設定する。
アサート : 呼び出し元が
obj の [[GetPrototypeOf]] および [[SetPrototypeOf]]
の両方の本質的な内部メソッドを上書きしないなら、internalSlotsList は [[Prototype]] を含む。
アサート : 呼び出し元が
obj の [[SetPrototypeOf]] , [[IsExtensible]] , [[PreventExtensions]]
の全ての本質的な内部メソッドを上書きしないなら、internalSlotsList は [[Extensible]] を含む。
もし internalSlotsList が [[Extensible]]
を含むなら、obj .[[Extensible]] を true
に設定する。
obj を返す。
注
本仕様内では、エキゾチックオブジェクト は 抽象操作 (例えば
ArrayCreate や BoundFunctionCreate )内でまず
MakeBasicObject
を呼び出して基本となるオブジェクトを取得し、その後そのオブジェクトの内部メソッドの一部または全部を上書きすることで作成されます。エキゾチックオブジェクト作成のカプセル化のため、これらの操作以外で本質的内部メソッドが変更されることはありません。
7.3.2 Get ( O , P )
抽象操作 Get は、引数 O (オブジェクト)と P (プロパティキー )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。これはオブジェクトの特定のプロパティ値を取得するために使われます。呼び出されたとき、次の手順を実行します:
? O .[[Get]] (P , O ) を返す。
7.3.3 GetV ( V , P )
抽象操作 GetV は、引数 V (ECMAScript 言語値 )と
P (プロパティキー )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。これは ECMAScript 言語値
の特定のプロパティ値を取得するために使われます。値がオブジェクトでない場合、型に応じたラッパーオブジェクトを使ってプロパティ検索が行われます。呼び出されたとき、次の手順を実行します:
O を ? ToObject (V ) とする。
? O .[[Get]] (P , V ) を返す。
7.3.4 Set ( O , P , V ,
Throw )
抽象操作 Set は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript
言語値 )、Throw (Boolean)を受け取り、normal completion
containing な unused 、または throw completion
を返します。これはオブジェクトの特定のプロパティ値を設定するために使われます。V はプロパティに設定する新しい値です。呼び出されたとき、次の手順を実行します:
success を ? O .[[Set]] (P , V , O )
とする。
もし success が false かつ Throw が
true なら、TypeError 例外を投げる。
unused を返す。
7.3.5 CreateDataProperty ( O , P , V
)
抽象操作 CreateDataProperty は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript 言語値 )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これはオブジェクトに新しい自身のプロパティを生成するために使用されます。呼び出されたとき、次の手順を実行します:
newDesc を PropertyDescriptor { [[Value]] :
V , [[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : true } とする。
? O .[[DefineOwnProperty]] (P ,
newDesc ) を返す。
注
この抽象操作は、ECMAScript
言語の代入演算子によって作成されるプロパティと同じデフォルト属性でプロパティを生成します。通常、このプロパティは既存しません。もし既に存在し、それが設定可能でない場合や
O が拡張不可能な場合、[[DefineOwnProperty]] は
false を返します。
7.3.6 CreateDataPropertyOrThrow ( O , P ,
V )
抽象操作 CreateDataPropertyOrThrow は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript 言語値 )を受け取り、normal completion
containing な unused または throw completion
を返します。これはオブジェクトに新しい自身のプロパティを生成するために使用されます。要求されたプロパティ更新ができない場合は TypeError
例外を投げます。呼び出されたとき、次の手順を実行します:
success を ? CreateDataProperty (O ,
P , V ) とする。
もし success が false なら、TypeError 例外を投げる。
unused を返す。
注
この抽象操作は、ECMAScript
言語の代入演算子によって作成されるプロパティと同じデフォルト属性でプロパティを生成します。通常、このプロパティは既存しません。もし既に存在し、それが設定可能でない場合や
O が拡張不可能な場合、[[DefineOwnProperty]] は
false を返し、この操作は TypeError 例外を投げます。
7.3.7 CreateNonEnumerableDataPropertyOrThrow ( O ,
P , V )
抽象操作 CreateNonEnumerableDataPropertyOrThrow は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript
言語値 )を受け取り、unused を返します。これは 通常オブジェクト に新しい列挙不可の自身のプロパティを生成するために使用されます。呼び出されたとき、次の手順を実行します:
アサート :
O は通常の拡張可能なオブジェクトで、非設定可能なプロパティを持たない。
newDesc を PropertyDescriptor { [[Value]] :
V , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true } とする。
! DefinePropertyOrThrow (O ,
P , newDesc ) を実行する。
unused を返す。
注
この抽象操作は、ECMAScript
言語の代入演算子で生成されるプロパティと同じデフォルト属性でプロパティを作成しますが、列挙不可となる点が異なります。通常、このプロパティは既存しません。もし既に存在する場合、DefinePropertyOrThrow
は常に正常に完了することが保証されています。
7.3.8 DefinePropertyOrThrow ( O , P ,
desc )
抽象操作 DefinePropertyOrThrow は、引数 O (オブジェクト)、P (プロパティキー )、desc (プロパティディスクリプタ )を受け取り、normal completion
containing な unused または throw completion
を返します。これは、要求されたプロパティ更新ができない場合 TypeError 例外を投げる形で、オブジェクトの [[DefineOwnProperty]] 内部メソッドを呼び出すために使用されます。呼び出されたとき、次の手順を実行します:
success を ? O .[[DefineOwnProperty]] (P , desc )
とする。
もし success が false なら、TypeError 例外を投げる。
unused を返す。
7.3.9 DeletePropertyOrThrow ( O , P )
抽象操作 DeletePropertyOrThrow は、引数 O (オブジェクト)と P (プロパティキー )を受け取り、normal completion
containing な unused または throw completion
を返します。これはオブジェクトの特定の自身のプロパティを削除するために使われます。そのプロパティが設定可能でない場合は例外を投げます。呼び出されたとき、次の手順を実行します:
success を ? O .[[Delete]] (P ) とする。
もし success が false なら、TypeError 例外を投げる。
unused を返す。
7.3.10 GetMethod ( V , P )
抽象操作 GetMethod は、引数 V (ECMAScript 言語値 )と
P (プロパティキー )を受け取り、normal completion
containing な 関数オブジェクト または undefined 、もしくは
throw completion
を返します。これはプロパティ値が関数であることが期待される場合に、ECMAScript 言語値
の特定プロパティ値を取得するために使用されます。呼び出されたとき、次の手順を実行します:
func を ? GetV (V , P ) とする。
もし func が undefined または null
なら、undefined を返す。
もし IsCallable (func ) が
false なら、TypeError 例外を投げる。
func を返す。
7.3.11 HasProperty ( O , P )
抽象操作 HasProperty は、引数 O (オブジェクト)と P (プロパティキー )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これはオブジェクトが指定された プロパティキー
を持つかどうかを判定するために使われます。プロパティは自身または継承されたものでかまいません。呼び出されたとき、次の手順を実行します:
? O .[[HasProperty]] (P ) を返す。
7.3.12 HasOwnProperty ( O , P )
抽象操作 HasOwnProperty は、引数 O (オブジェクト)と P (プロパティキー )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これはオブジェクトが指定された プロパティキー
を自身のプロパティとして持つかどうかを判定するために使われます。呼び出されたとき、次の手順を実行します:
desc を ? O .[[GetOwnProperty]] (P ) とする。
もし desc が undefined なら false を返す。
true を返す。
7.3.13 Call ( F , V [ ,
argumentsList ] )
抽象操作 Call は、引数 F (ECMAScript
言語値 )、V (ECMAScript
言語値 )、および省略可能な argumentsList (ECMAScript
言語値のリスト )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。これは [[Call]] 内部メソッドを呼び出すために使われます。F は 関数オブジェクト 、V はその [[Call]] の this 値、argumentsList
は内部メソッドの該当引数に渡される値です。argumentsList が省略された場合は新しい空の リスト が使用されます。呼び出されたとき、次の手順を実行します:
もし argumentsList が省略された場合、argumentsList を新しい空の リスト に設定する。
もし IsCallable (F ) が
false なら、TypeError 例外を投げる。
? F .[[Call]] (V , argumentsList ) を返す。
7.3.14 Construct ( F [ , argumentsList [ ,
newTarget ] ] )
抽象操作 Construct は、引数 F (コンストラクタ )、および省略可能な argumentsList (リスト :ECMAScript
言語値 のリスト)、newTarget (コンストラクタ )を受け取り、normal completion
containing なオブジェクト、または throw completion
を返します。これは 関数オブジェクト の [[Construct]]
内部メソッドを呼び出すために使われます。argumentsList および newTarget
は内部メソッドの対応する引数として渡されます。argumentsList が省略された場合は新しい空の リスト
が値として使われます。newTarget が省略された場合は F が値として使われます。呼び出されたとき、次の手順を実行します:
もし newTarget が省略された場合、newTarget を F に設定する。
もし argumentsList が省略された場合、argumentsList を新しい空の リスト に設定する。
? F .[[Construct]] (argumentsList ,
newTarget ) を返す。
注
newTarget が省略された場合、この操作は new F(...argumentsList) と同等です。
7.3.15 SetIntegrityLevel ( O , level )
抽象操作 SetIntegrityLevel は、引数 O (オブジェクト)、level (sealed
または frozen )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これはオブジェクトの自身のプロパティの集合を固定するために使われます。呼び出されたとき、次の手順を実行します:
status を ? O .[[PreventExtensions]] ()
とする。
もし status が false なら、false を返す。
keys を ? O .[[OwnPropertyKeys]] ()
とする。
もし level が sealed なら、
keys の各要素 k について、
? DefinePropertyOrThrow (O ,
k , PropertyDescriptor { [[Configurable]] :
false }) を実行する。
それ以外の場合、
アサート :
level は frozen である。
keys の各要素 k について、
currentDesc を ? O .[[GetOwnProperty]] (k ) とする。
もし currentDesc が undefined でなければ、
もし IsAccessorDescriptor (currentDesc )
が true なら、
desc を PropertyDescriptor { [[Configurable]] :
false } とする。
それ以外の場合、
desc を PropertyDescriptor { [[Configurable]] :
false , [[Writable]] :
false } とする。
? DefinePropertyOrThrow (O ,
k , desc ) を実行する。
true を返す。
7.3.16 TestIntegrityLevel ( O , level )
抽象操作 TestIntegrityLevel は、引数 O (オブジェクト)、level (sealed
または frozen )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これはオブジェクトの自身のプロパティの集合が固定されているかどうかを判定するために使われます。呼び出されたとき、次の手順を実行します:
extensible を ? IsExtensible (O ) とする。
もし extensible が true なら、false を返す。
注:オブジェクトが拡張可能である場合、そのプロパティは検査されません。
keys を ? O .[[OwnPropertyKeys]] ()
とする。
keys の各要素 k について、
currentDesc を ? O .[[GetOwnProperty]] (k ) とする。
もし currentDesc が undefined でなければ、
もし currentDesc .[[Configurable]] が
true なら、false を返す。
もし level が frozen かつ IsDataDescriptor (currentDesc )
が true なら、
もし currentDesc .[[Writable]]
が true なら、false を返す。
true を返す。
7.3.17 CreateArrayFromList ( elements )
抽象操作 CreateArrayFromList は、引数 elements (リスト :ECMAScript
言語値 のリスト)を受け取り、配列を返します。これは elements
で与えられた要素を持つ配列を生成するために使われます。呼び出されたとき、次の手順を実行します:
array を ! ArrayCreate (0) とする。
n を 0 とする。
elements の各要素 e について、
! CreateDataPropertyOrThrow (array ,
! ToString (𝔽 (n )),
e ) を実行する。
n を n + 1 に設定する。
array を返す。
7.3.18 LengthOfArrayLike ( obj )
抽象操作 LengthOfArrayLike は、引数 obj (オブジェクト)を受け取り、normal completion
containing な非負の 整数 または throw completion
を返します。これは配列様オブジェクトの "length" プロパティの値を返します。呼び出されたとき、次の手順を実行します:
ℝ (? ToLength (? Get (obj ,
"length" ))) を返す。
配列様オブジェクト とは、この操作が normal
completion を返す任意のオブジェクトです。
注1
通常、配列様オブジェクトは
整数インデックス 名のプロパティも持ちますが、この定義の要件ではありません。
注2
配列や String オブジェクトは配列様オブジェクトの例です。
7.3.19 CreateListFromArrayLike ( obj [ ,
validElementTypes ] )
抽象操作 CreateListFromArrayLike は、引数 obj (ECMAScript 言語値 )と省略可能な
validElementTypes (all または
property-key )を受け取り、normal completion
containing な リスト :ECMAScript 言語値 のリスト、または throw completion
を返します。これは obj のインデックス付きプロパティによって与えられる要素で構成される リスト 値を生成するために使われます。validElementTypes
は要素として許容される値の型を示します。呼び出されたとき、次の手順を実行します:
もし validElementTypes が指定されていなければ、validElementTypes を
all に設定する。
もし obj がオブジェクトでない なら、TypeError
例外を投げる。
len を ? LengthOfArrayLike (obj ) とする。
list を新しい空の リスト
とする。
index を 0 とする。
index < len の間、繰り返し:
indexName を ! ToString (𝔽 (index )) とする。
next を ? Get (obj ,
indexName ) とする。
もし validElementTypes が property-key かつ
next が プロパティキー
でないなら、TypeError 例外を投げる。
next を list に追加する。
index を index + 1 に設定する。
list を返す。
7.3.20 Invoke ( V , P [ ,
argumentsList ] )
抽象操作 Invoke は、引数 V (ECMAScript
言語値 )、P (プロパティキー )、および省略可能な argumentsList (リスト :ECMAScript 言語値 のリスト)を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。これは ECMAScript 言語値
のメソッドプロパティを呼び出すために使われます。V はプロパティ検索元かつ呼び出し時の this
値として機能します。argumentsList はメソッドに渡す引数のリストです。argumentsList が省略された場合は新しい空の
リスト
が値として使われます。呼び出されたとき、次の手順を実行します:
もし argumentsList が指定されていなければ、argumentsList を新しい空の リスト に設定する。
func を ? GetV (V , P ) とする。
? Call (func , V ,
argumentsList ) を返す。
7.3.21 OrdinaryHasInstance ( C , O )
抽象操作 OrdinaryHasInstance は、引数 C (ECMAScript
言語値 )、O (ECMAScript
言語値 )を受け取り、normal completion
containing な Boolean または throw completion
を返します。これは O が C
によって提供されるインスタンスオブジェクト継承パスから継承しているかどうかを判定するデフォルトアルゴリズムです。呼び出されたとき、次の手順を実行します:
もし IsCallable (C ) が
false なら、false を返す。
もし C が [[BoundTargetFunction]] 内部スロットを持つなら、
BC を C .[[BoundTargetFunction]]
とする。
? InstanceofOperator (O ,
BC ) を返す。
もし O がオブジェクトでない なら、false を返す。
P を ? Get (C ,
"prototype" ) とする。
もし P がオブジェクトでない なら、TypeError
例外を投げる。
繰り返し:
O を ? O .[[GetPrototypeOf]] () に設定する。
もし O が null なら、false を返す。
もし SameValue (P ,
O ) が true なら、true を返す。
7.3.22 SpeciesConstructor ( O ,
defaultConstructor )
抽象操作 SpeciesConstructor は、引数 O (オブジェクト)、defaultConstructor (コンストラクタ )を受け取り、normal completion
containing な コンストラクタ 、または throw completion
を返します。これは O から派生した新しいオブジェクトを作成するために使用されるべき コンストラクタ
を取得するために使われます。defaultConstructor は、O から コンストラクタ %Symbol.species% プロパティが見つからなかった場合に使用される
コンストラクタ
です。呼び出されたとき、次の手順を実行します:
C を ? Get (O ,
"constructor" ) とする。
もし C が undefined なら、defaultConstructor を返す。
もし C がオブジェクトでない なら、TypeError
例外を投げる。
S を ? Get (C , %Symbol.species% ) とする。
もし S が undefined または null
なら、defaultConstructor を返す。
もし IsConstructor (S ) が
true なら、S を返す。
TypeError 例外を投げる。
7.3.23 EnumerableOwnProperties ( O , kind )
抽象操作 EnumerableOwnProperties は、引数
O (オブジェクト)、kind (key 、value 、または
key+value )を受け取り、normal completion
containing な リスト :ECMAScript 言語値 のリスト、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
ownKeys を ? O .[[OwnPropertyKeys]] () とする。
results を新しい空の リスト
とする。
ownKeys の各要素 key について:
もし key が文字列 なら、
desc を ? O .[[GetOwnProperty]] (key )
とする。
もし desc が undefined でなく、かつ
desc .[[Enumerable]] が
true なら、
もし kind が key なら、
key を results に追加する。
それ以外の場合、
value を ? Get (O ,
key ) とする。
もし kind が value なら、
value を results に追加する。
それ以外の場合、
アサート :
kind は
key+value である。
entry を CreateArrayFromList («key ,
value » ) とする。
entry を results に追加する。
results を返す。
7.3.24 GetFunctionRealm ( obj )
抽象操作 GetFunctionRealm は、引数 obj (関数オブジェクト )を受け取り、normal completion
containing な Realm Record または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし obj が [[Realm]] 内部スロットを持つなら、
obj .[[Realm]] を返す。
もし obj が束縛関数エキゾチックオブジェクト なら、
boundTargetFunction を obj .[[BoundTargetFunction]] とする。
? GetFunctionRealm (boundTargetFunction )
を返す。
もし obj がProxy エキゾチックオブジェクト なら、
? ValidateNonRevokedProxy (obj )
を実行する。
proxyTarget を obj .[[ProxyTarget]]
とする。
アサート :
proxyTarget は 関数オブジェクト である。
? GetFunctionRealm (proxyTarget )
を返す。
現在の Realm Record を返す。
注
ステップ 4
に到達するのは、obj が [[Realm]] 内部スロットを持たない非標準の エキゾチックオブジェクト の場合のみです。
7.3.25 CopyDataProperties ( target , source ,
excludedItems )
抽象操作 CopyDataProperties は、引数 target (オブジェクト)、source (ECMAScript
言語値 )、excludedItems (プロパティキーのリスト )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし source が undefined または null
なら、unused を返す。
from を ! ToObject (source ) とする。
keys を ? from .[[OwnPropertyKeys]] () とする。
keys の各要素 nextKey について、
excluded を false に設定する。
excludedItems の各要素 e について、
もし SameValue (e ,
nextKey ) が true なら、
excluded を true に設定する。
もし excluded が false なら、
desc を ? from .[[GetOwnProperty]] (nextKey )
とする。
もし desc が undefined でなく、かつ
desc .[[Enumerable]] が
true なら、
propValue を ? Get (from ,
nextKey ) とする。
! CreateDataPropertyOrThrow (target ,
nextKey , propValue ) を実行する。
unused を返す。
注
ここで渡される target は常に新しく作成されたオブジェクトであり、エラーが投げられた場合に直接アクセスすることはできません。
7.3.26 PrivateElementFind ( O , P )
抽象操作 PrivateElementFind は、引数 O (オブジェクト)、P (Private
Name )を受け取り、PrivateElement または
empty を返します。呼び出されたとき、次の手順を実行します:
もし O .[[PrivateElements]] が PrivateElement
pe を含み、かつ pe .[[Key]] が P
であるなら、
pe を返す。
empty を返す。
7.3.27 PrivateFieldAdd ( O , P ,
value )
抽象操作 PrivateFieldAdd は、引数 O (オブジェクト)、P (Private
Name )、value (ECMAScript
言語値 )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし ホスト が Webブラウザなら、
? HostEnsureCanAddPrivateElement (O )
を実行する。
entry を PrivateElementFind (O ,
P ) とする。
もし entry が empty でないなら、TypeError
例外を投げる。
PrivateElement {
[[Key]] : P , [[Kind]] :
field , [[Value]] : value } を
O .[[PrivateElements]] に追加する。
unused を返す。
7.3.28 PrivateMethodOrAccessorAdd ( O , method
)
抽象操作 PrivateMethodOrAccessorAdd は、引数 O (オブジェクト)、method (PrivateElement )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
アサート :
method .[[Kind]] は method または
accessor である。
もし ホスト が Webブラウザなら、
? HostEnsureCanAddPrivateElement (O )
を実行する。
entry を PrivateElementFind (O ,
method .[[Key]] ) とする。
もし entry が empty でないなら、TypeError
例外を投げる。
method を O .[[PrivateElements]] に追加する。
unused を返す。
注
プライベートメソッドおよびアクセサの値はインスタンス間で共有されます。この操作はメソッドやアクセサのコピーを新たに作成しません。
7.3.29 HostEnsureCanAddPrivateElement ( O )
ホスト定義 抽象操作
HostEnsureCanAddPrivateElement は、引数 O (オブジェクト)を受け取り、normal completion
containing な unused または throw completion
を返します。これは ホスト環境 が特定の ホスト定義 エキゾチックオブジェクト
へのプライベート要素の追加を防ぐことができるようにします。
HostEnsureCanAddPrivateElement の実装は以下の要件を満たさなければなりません:
HostEnsureCanAddPrivateElement のデフォルト実装は NormalCompletion (unused )
を返す。
この抽象操作は ECMAScript の ホスト が
Webブラウザの場合のみ呼び出されます。
7.3.30 PrivateGet ( O , P )
抽象操作 PrivateGet は、引数 O (オブジェクト)、P (Private Name )を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。呼び出されたとき、次の手順を実行します:
entry を PrivateElementFind (O ,
P ) とする。
もし entry が empty なら、TypeError
例外を投げる。
もし entry .[[Kind]] が field または
method なら、
entry .[[Value]] を返す。
アサート :
entry .[[Kind]] は accessor
である。
もし entry .[[Get]] が undefined
なら、TypeError 例外を投げる。
getter を entry .[[Get]] とする。
? Call (getter , O ) を返す。
7.3.31 PrivateSet ( O , P , value )
抽象操作 PrivateSet は、引数 O (オブジェクト)、P (Private
Name )、value (ECMAScript
言語値 )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
entry を PrivateElementFind (O ,
P ) とする。
もし entry が empty なら、TypeError
例外を投げる。
もし entry .[[Kind]] が field なら、
entry .[[Value]] を value に設定する。
それ以外で entry .[[Kind]] が method
なら、
TypeError 例外を投げる。
それ以外の場合、
アサート :
entry .[[Kind]] は
accessor である。
もし entry .[[Set]] が
undefined なら、TypeError 例外を投げる。
setter を entry .[[Set]] とする。
? Call (setter , O ,
« value ») を実行する。
unused を返す。
7.3.32 DefineField ( receiver , fieldRecord )
抽象操作 DefineField は、引数 receiver (オブジェクト)、fieldRecord (ClassFieldDefinition
Record )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
fieldName を fieldRecord .[[Name]] とする。
initializer を fieldRecord .[[Initializer]]
とする。
もし initializer が empty でないなら、
initValue を ? Call (initializer ,
receiver ) とする。
それ以外の場合、
initValue を undefined とする。
もし fieldName が Private Name なら、
? PrivateFieldAdd (receiver ,
fieldName , initValue ) を実行する。
それ以外の場合、
アサート :
fieldName は プロパティキー である。
? CreateDataPropertyOrThrow (receiver ,
fieldName , initValue ) を実行する。
unused を返す。
7.3.33 InitializeInstanceElements ( O ,
constructor )
抽象操作 InitializeInstanceElements は、引数 O (オブジェクト)、constructor (ECMAScript
関数オブジェクト )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
methods を constructor .[[PrivateMethods]]
とする。
methods の各 PrivateElement
method について、
? PrivateMethodOrAccessorAdd (O ,
method ) を実行する。
fields を constructor .[[Fields]] とする。
fields の各要素 fieldRecord について、
? DefineField (O ,
fieldRecord ) を実行する。
unused を返す。
7.3.34 AddValueToKeyedGroup ( groups , key ,
value )
抽象操作 AddValueToKeyedGroup は、引数 groups (リスト :Record (フィールド [[Key]] (ECMAScript 言語値 )、[[Elements]] (リスト :ECMAScript
言語値 )))、key (ECMAScript
言語値 )、value (ECMAScript
言語値 )を受け取り、unused を返します。呼び出されたとき、次の手順を実行します:
groups の各 Record { [[Key]] , [[Elements]] } g
について:
もし SameValue (g .[[Key]] , key ) が true なら、
アサート : この条件を満たす groups
の要素は正確に1つだけ。
value を g .[[Elements]]
に追加する。
unused を返す。
group を Record { [[Key]] : key , [[Elements]] :
« value » } とする。
group を groups に追加する。
unused を返す。
7.3.35 GroupBy ( items , callback ,
keyCoercion )
抽象操作 GroupBy は、引数 items (ECMAScript
言語値 )、callback (ECMAScript
言語値 )、keyCoercion (property または
collection )を受け取り、normal completion
containing な リスト :Record (フィールド [[Key]] (ECMAScript 言語値 )、[[Elements]] (リスト :ECMAScript 言語値 )))、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
? RequireObjectCoercible (items )
を実行する。
もし IsCallable (callback ) が
false なら、TypeError 例外を投げる。
groups を新しい空の リスト
とする。
iteratorRecord を ? GetIterator (items ,
sync ) とする。
k を 0 とする。
繰り返し:
もし k ≥ 253 - 1 なら、
error を ThrowCompletion (新しく作成された
TypeError オブジェクト) とする。
? IteratorClose (iteratorRecord ,
error ) を返す。
next を ? IteratorStepValue (iteratorRecord )
とする。
もし next が done なら、
groups を返す。
value を next とする。
key を Completion (Call (callback ,
undefined , « value , 𝔽 (k ) » )) とする。
IfAbruptCloseIterator (key ,
iteratorRecord ) を実行する。
もし keyCoercion が property なら、
key を Completion (ToPropertyKey (key ))
に設定する。
IfAbruptCloseIterator (key ,
iteratorRecord ) を実行する。
それ以外の場合、
アサート : keyCoercion は
collection である。
key を CanonicalizeKeyedCollectionKey (key )
に設定する。
AddValueToKeyedGroup (groups ,
key , value ) を実行する。
k を k + 1 に設定する。
7.3.36 SetterThatIgnoresPrototypeProperties ( thisValue ,
home , p , v )
抽象操作 SetterThatIgnoresPrototypeProperties は、引数 thisValue (ECMAScript
言語値 )、home (オブジェクト)、p (プロパティキー )、v (ECMAScript 言語値 )を受け取り、normal completion
containing な unused または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし thisValue がオブジェクトでない なら、
TypeError 例外を投げる。
もし SameValue (thisValue ,
home ) が true なら、
注:ここで例外を投げることで、home オブジェクトのデータプロパティ が書き込み不可である場合の厳格モードコード での代入をエミュレートする。
TypeError 例外を投げる。
desc を ? thisValue .[[GetOwnProperty]] (p ) とする。
もし desc が undefined なら、
? CreateDataPropertyOrThrow (thisValue ,
p , v ) を実行する。
それ以外の場合、
? Set (thisValue ,
p , v , true ) を実行する。
unused を返す。
7.4 イテレータオブジェクトに対する操作
共通のイテレーションインターフェース(27.1 )を参照。
7.4.1 イテレータレコード
イテレータレコード とは、Record 値であり、イテレータ または 非同期イテレータ と next
メソッドをカプセル化するために使用されます。
イテレータレコードは、表15 に挙げられているフィールドを持ちます。
表15: イテレータレコード のフィールド
7.4.2 GetIteratorDirect ( obj )
抽象操作 GetIteratorDirect は、引数 obj (オブジェクト)を受け取り、normal completion
containing な イテレータレコード または throw completion
を返します。呼び出されたとき、次の手順を実行します:
nextMethod を ? Get (obj ,
"next" ) とする。
iteratorRecord を イテレータレコード { [[Iterator]] : obj , [[NextMethod]] : nextMethod , [[Done]] : false } とする。
iteratorRecord を返す。
7.4.3 GetIteratorFromMethod ( obj , method )
抽象操作 GetIteratorFromMethod は、引数 obj (ECMAScript
言語値 )、method (関数オブジェクト )を受け取り、normal completion
containing な イテレータレコード または throw completion
を返します。呼び出されたとき、次の手順を実行します:
iterator を ? Call (method ,
obj ) とする。
もし iterator がオブジェクトでない なら、TypeError
例外を投げる。
? GetIteratorDirect (iterator ) を返す。
7.4.4 GetIterator ( obj , kind )
抽象操作 GetIterator は、引数 obj (ECMAScript
言語値 )、kind (sync または
async )を受け取り、normal completion
containing な イテレータレコード または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし kind が async なら、
method を ? GetMethod (obj , %Symbol.asyncIterator% )
とする。
もし method が undefined なら、
syncMethod を ? GetMethod (obj ,
%Symbol.iterator% )
とする。
もし syncMethod が undefined
なら、TypeError 例外を投げる。
syncIteratorRecord を ? GetIteratorFromMethod (obj ,
syncMethod ) とする。
CreateAsyncFromSyncIterator (syncIteratorRecord )
を返す。
それ以外の場合、
method を ? GetMethod (obj , %Symbol.iterator% ) とする。
もし method が undefined なら、TypeError
例外を投げる。
? GetIteratorFromMethod (obj ,
method ) を返す。
7.4.5 GetIteratorFlattenable ( obj ,
primitiveHandling )
抽象操作 GetIteratorFlattenable は、引数 obj (ECMAScript
言語値 )、primitiveHandling (iterate-string-primitives
または reject-primitives )を受け取り、normal completion
containing な イテレータレコード または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし obj がオブジェクトでない なら、
もし primitiveHandling が reject-primitives
なら、TypeError 例外を投げる。
アサート :
primitiveHandling は iterate-string-primitives
である。
もし obj が文字列でない なら、TypeError
例外を投げる。
method を ? GetMethod (obj , %Symbol.iterator% ) とする。
もし method が undefined なら、
iterator を obj とする。
それ以外の場合、
iterator を ? Call (method ,
obj ) とする。
もし iterator がオブジェクトでない なら、TypeError
例外を投げる。
? GetIteratorDirect (iterator ) を返す。
7.4.6 IteratorNext ( iteratorRecord [ , value
] )
抽象操作 IteratorNext は、引数 iteratorRecord (イテレータレコード )、省略可能な
value (ECMAScript 言語値 )を受け取り、normal completion
containing なオブジェクト、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
もし value が指定されていなければ、
result を Completion (Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] )) とする。
それ以外の場合、
result を Completion (Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] , « value »)) とする。
もし result が throw
completion なら、
iteratorRecord .[[Done]] を
true に設定する。
? result を返す。
result を ! result に設定する。
もし result がオブジェクトでない なら、
iteratorRecord .[[Done]] を
true に設定する。
TypeError 例外を投げる。
result を返す。
7.4.7 IteratorComplete ( iteratorResult )
抽象操作 IteratorComplete は、引数 iteratorResult (オブジェクト)を受け取り、normal completion
containing な Boolean または throw completion
を返します。呼び出されたとき、次の手順を実行します:
ToBoolean (? Get (iteratorResult ,
"done" )) を返す。
7.4.8 IteratorValue ( iteratorResult )
抽象操作 IteratorValue は、引数 iteratorResult (オブジェクト)を受け取り、normal completion
containing な ECMAScript 言語値 または
throw completion
を返します。呼び出されたとき、次の手順を実行します:
? Get (iteratorResult ,
"value" ) を返す。
7.4.9 IteratorStep ( iteratorRecord )
抽象操作 IteratorStep は、引数 iteratorRecord (イテレータレコード )を受け取り、normal completion
containing なオブジェクトまたは done 、あるいは throw completion
を返します。これは iteratorRecord .[[Iterator]] から
iteratorRecord .[[NextMethod]] を呼び出して次の値を取得し、イテレータが終端に到達した場合は
done を、そうでなければ IteratorResult オブジェクト
を返します。呼び出されたとき、次の手順を実行します:
result を ? IteratorNext (iteratorRecord ) とする。
done を Completion (IteratorComplete (result )) とする。
もし done が throw
completion なら、
iteratorRecord .[[Done]] を
true に設定する。
? done を返す。
done を ! done に設定する。
もし done が true なら、
iteratorRecord .[[Done]] を
true に設定する。
done を返す。
result を返す。
7.4.10 IteratorStepValue ( iteratorRecord )
抽象操作 IteratorStepValue は、引数 iteratorRecord (イテレータレコード )を受け取り、normal completion
containing な ECMAScript 言語値 または
done 、あるいは throw
completion を返します。これは iteratorRecord .[[Iterator]] から iteratorRecord .[[NextMethod]] を呼び出して次の値を取得し、イテレータが終端に到達した場合は
done を、そうでなければ IteratorResult オブジェクト
の値を返します。呼び出されたとき、次の手順を実行します:
result を ? IteratorStep (iteratorRecord ) とする。
もし result が done なら、
done を返す。
value を Completion (IteratorValue (result )) とする。
もし value が throw
completion なら、
iteratorRecord .[[Done]] を
true に設定する。
? value を返す。
7.4.11 IteratorClose ( iteratorRecord ,
completion )
抽象操作 IteratorClose は、引数 iteratorRecord (イテレータレコード )、completion (Completion
Record )を受け取り、Completion
Record を返します。これは イテレータ
に対し、完了状態になったときに通常行うべき処理を通知するために使われます。呼び出されたとき、次の手順を実行します:
アサート :
iteratorRecord .[[Iterator]] がオブジェクト である。
iterator を iteratorRecord .[[Iterator]]
とする。
innerResult を Completion (GetMethod (iterator ,
"return" )) とする。
もし innerResult が normal
completion なら、
return を innerResult .[[Value]]
とする。
もし return が undefined
なら、? completion を返す。
innerResult を Completion (Call (return ,
iterator )) に設定する。
もし completion が throw
completion なら、? completion を返す。
もし innerResult が throw
completion なら、? innerResult を返す。
もし innerResult .[[Value]] がオブジェクトでない なら、TypeError
例外を投げる。
? completion を返す。
7.4.12 IfAbruptCloseIterator ( value ,
iteratorRecord )
IfAbruptCloseIterator は イテレータレコード
を使う一連のアルゴリズムステップの省略記法です。次の形式のアルゴリズムステップ:
IfAbruptCloseIterator (value ,
iteratorRecord )。
は、次と同じ意味になります:
アサート :
value は Completion
Record である。
もし value が abrupt
completion なら、? IteratorClose (iteratorRecord ,
value ) を返す。
それ以外の場合、value を ! value に設定する。
7.4.13 AsyncIteratorClose ( iteratorRecord ,
completion )
抽象操作 AsyncIteratorClose は、引数 iteratorRecord (イテレータレコード )、completion (Completion
Record )を受け取り、Completion
Record を返します。これは 非同期イテレータ
に対し、完了状態になったときに通常行うべき処理を通知するために使われます。呼び出されたとき、次の手順を実行します:
アサート :
iteratorRecord .[[Iterator]] がオブジェクト である。
iterator を iteratorRecord .[[Iterator]]
とする。
innerResult を Completion (GetMethod (iterator ,
"return" )) とする。
もし innerResult が normal
completion なら、
return を innerResult .[[Value]]
とする。
もし return が undefined
なら、? completion を返す。
innerResult を Completion (Call (return ,
iterator )) に設定する。
もし innerResult が normal
completion なら、innerResult を Completion (Await (innerResult .[[Value]] )) に設定する。
もし completion が throw
completion なら、? completion を返す。
もし innerResult が throw
completion なら、? innerResult を返す。
もし innerResult .[[Value]] がオブジェクトでない なら、TypeError
例外を投げる。
? completion を返す。
7.4.14 CreateIteratorResultObject ( value ,
done )
抽象操作 CreateIteratorResultObject は、引数 value (ECMAScript
言語値 )、done (Boolean)を受け取り、IteratorResult
インターフェース に準拠するオブジェクトを返します。これはIteratorResult
インターフェース に準拠するオブジェクトを生成します。呼び出されたとき、次の手順を実行します:
obj を OrdinaryObjectCreate (%Object.prototype% )
とする。
! CreateDataPropertyOrThrow (obj ,
"value" , value ) を実行する。
! CreateDataPropertyOrThrow (obj ,
"done" , done ) を実行する。
obj を返す。
7.4.15 CreateListIteratorRecord ( list )
抽象操作 CreateListIteratorRecord は、引数 list (リスト :ECMAScript 言語値 のリスト)を受け取り、イテレータレコード を返します。これは [[NextMethod]] が list の各要素を順に返す イテレータレコード を生成します。呼び出されたとき、次の手順を実行します:
closure を引数なしで list をキャプチャし、呼び出されたとき以下の手順を実行する新しい Abstract
Closure とする:
list の各要素 E について、
? GeneratorYield (CreateIteratorResultObject (E ,
false )) を実行する。
NormalCompletion (undefined )
を返す。
iterator を CreateIteratorFromClosure (closure ,
empty , %Iterator.prototype% )
とする。
イテレータレコード { [[Iterator]] : iterator , [[NextMethod]] : %GeneratorPrototype.next%, [[Done]] : false } を返す。
注
リストイテレータオブジェクト は ECMAScript
コードから直接アクセスできません。
7.4.16 IteratorToList ( iteratorRecord )
抽象操作 IteratorToList は、引数 iteratorRecord (イテレータレコード )を受け取り、normal completion
containing な リスト :ECMAScript 言語値 のリスト、または throw completion
を返します。呼び出されたとき、次の手順を実行します:
values を新しい空の リスト
とする。
繰り返し:
next を ? IteratorStepValue (iteratorRecord )
とする。
もし next が done なら、
values を返す。
next を values に追加する。
8 構文指向操作
この節で定義されているものに加えて、特化された 構文指向操作
が本仕様書の各所で定義されています。
8.1 実行時セマンティクス: 評価
構文指向操作
Evaluation は引数を取らず、Completion Record を返します。
注
この操作の定義は、本仕様書の「ECMAScript 言語」セクションに分散して記述されています。各定義は、関連する生成規則の定義箇所の直後に記載されています。
8.2 スコープ解析
8.2.1 静的セマンティクス: BoundNames
構文指向操作
BoundNames は引数を取らず、文字列のリスト を返します。
注
"*default*"
は、他の名前を持たないモジュールのデフォルトエクスポートに対する合成名として本仕様書内で使用されます。その名前でモジュールの [[Environment]] にエントリが作成され、対応する値が格納されます。また、モジュールに対して ResolveExport ( exportName [ ,
resolveSet ] ) を呼び出して "default"
という名前のエクスポートを解決すると、[[BindingName]] が
"*default*" である ResolvedBinding
Record が返され、これがモジュールの [[Environment]]
で上記の値に解決されます。これは仕様記述を容易にするためだけに行われており、匿名のデフォルトエクスポートも他のエクスポートと同様に解決できるようになっています。この
"*default*" という文字列は、ECMAScript コードやモジュールリンクアルゴリズムからアクセスされることはありません。
これは以下の生成規則ごとに分割定義されています:
束縛識別子
: 識別子
リスト を返す。その唯一の要素はStringValue であり、識別子 の値である。
束縛識別子
: yield
« "yield" »を返す。
束縛識別子
: await
« "await" »を返す。
レキシカル宣言
:
LetまたはConst
束縛リスト
;
束縛名 を束縛リスト について返す。
束縛リスト :
束縛リスト
,
レキシカル束縛
names1 を、束縛名 (束縛リスト について)とする。
names2 を、束縛名 (レキシカル束縛 について)とする。
リスト連結 によってnames1 とnames2 を結合して返す。
レキシカル束縛 :
束縛識別子
初期化子 オプション
束縛名 を束縛識別子 について返す。
レキシカル束縛 :
束縛パターン
初期化子
束縛名 を束縛パターン について返す。
変数宣言リスト
:
変数宣言リスト
,
変数宣言
names1 を 束縛名 (変数宣言リスト について)とする。
names2 を 束縛名 (変数宣言 について)とする。
リスト連結 によって names1 と
names2 を結合して返す。
変数宣言
:
束縛識別子
初期化子 オプション
束縛名 を束縛識別子 について返す。
変数宣言
:
束縛パターン
初期化子
束縛名 を束縛パターン について返す。
オブジェクト束縛パターン
:
{
}
新しい空のリスト を返す。
オブジェクト束縛パターン
:
{
束縛プロパティリスト
,
束縛残余プロパティ
}
names1 を 束縛名 (束縛プロパティリスト について)とする。
names2 を 束縛名 (束縛残余プロパティ について)とする。
リスト連結 によって names1 と
names2 を結合して返す。
配列束縛パターン
:
[
省略 オプション
]
新しい空のリスト を返す。
配列束縛パターン
:
[
省略 オプション
束縛残余要素
]
束縛名 を束縛残余要素 について返す。
配列束縛パターン
:
[
束縛要素リスト
,
省略 オプション
]
束縛名 を束縛要素リスト について返す。
配列束縛パターン
:
[
束縛要素リスト
,
省略 オプション
束縛残余要素
]
names1 を 束縛名 (束縛要素リスト について)とする。
names2 を 束縛名 (束縛残余要素 について)とする。
リスト連結 によって names1 と
names2 を結合して返す。
束縛プロパティリスト
:
束縛プロパティリスト
,
束縛プロパティ
names1 を 束縛名 (束縛プロパティリスト について)とする。
names2 を 束縛名 (束縛プロパティ について)とする。
リスト連結 によって names1 と
names2 を結合して返す。
束縛要素リスト
:
束縛要素リスト
,
省略束縛要素
names1 を 束縛名 (束縛要素リスト について)とする。
names2 を 束縛名 (省略束縛要素 について)とする。
リスト連結 によって names1 と
names2 を結合して返す。
省略束縛要素
:
省略 オプション
束縛要素
束縛名 を束縛要素 について返す。
束縛プロパティ :
プロパティ名
:
束縛要素
束縛名 を束縛要素 について返す。
単一名束縛
:
束縛識別子
初期化子 オプション
束縛名 を束縛識別子 について返す。
束縛要素 :
束縛パターン
初期化子 オプション
束縛名 を束縛パターン について返す。
For宣言 :
LetまたはConst
For束縛
束縛名 をFor束縛 について返す。
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
BoundNames を BindingIdentifier
に対して返す。
FunctionDeclaration
:
function
(
FormalParameters
)
{
FunctionBody
}
« "*default*" » を返す。
FormalParameters :
[空]
新しい空の List を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
names1 を BoundNames の FormalParameterList
で取得する。
names2 を BoundNames の FunctionRestParameter で取得する。
names1 と names2 の リスト連結 を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
names1 を BoundNames の FormalParameterList
で取得する。
names2 を BoundNames の FormalParameter で取得する。
names1 と names2 の リスト連結 を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals を ArrowFormalParameters
で、cover されている CoverParenthesizedExpressionAndArrowParameterList
から取得する。
formals の BoundNames を返す。
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
BoundNames を BindingIdentifier
に対して返す。
GeneratorDeclaration
:
function
*
(
FormalParameters
)
{
GeneratorBody
}
« "*default*" » を返す。
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
BoundNames を BindingIdentifier
に対して返す。
AsyncGeneratorDeclaration
:
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
« "*default*" » を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
BoundNames を BindingIdentifier
に対して返す。
ClassDeclaration :
class
ClassTail
« "*default*" » を返す。
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
BoundNames を BindingIdentifier
に対して返す。
AsyncFunctionDeclaration
:
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
« "*default*" » を返す。
CoverCallExpressionAndAsyncArrowHead
:
MemberExpression
Arguments
head を AsyncArrowHead で、cover されている CoverCallExpressionAndAsyncArrowHead
から取得する。
head の BoundNames を返す。
ImportDeclaration
:
import
ImportClause
FromClause
WithClause opt
;
BoundNames を ImportClause に対して返す。
ImportDeclaration
:
import
ModuleSpecifier
WithClause opt
;
新しい空の List を返す。
ImportClause :
ImportedDefaultBinding
,
NameSpaceImport
names1 を BoundNames の ImportedDefaultBinding で取得する。
names2 を BoundNames の NameSpaceImport で取得する。
names1 と names2 の リスト連結 を返す。
ImportClause :
ImportedDefaultBinding
,
NamedImports
names1 を BoundNames の ImportedDefaultBinding で取得する。
names2 を BoundNames の NamedImports で取得する。
names1 と names2 の リスト連結 を返す。
NamedImports :
{
}
新しい空の List を返す。
ImportsList :
ImportsList
,
ImportSpecifier
names1 を BoundNames の ImportsList で取得する。
names2 を BoundNames の ImportSpecifier で取得する。
names1 と names2 の リスト連結 を返す。
ImportSpecifier :
ModuleExportName
as
ImportedBinding
BoundNames を ImportedBinding に対して返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
新しい空の List を返す。
ExportDeclaration
:
export
VariableStatement
BoundNames を VariableStatement
に対して返す。
ExportDeclaration
:
export
Declaration
BoundNames を Declaration に対して返す。
ExportDeclaration
:
export
default
HoistableDeclaration
declarationNames を BoundNames の HoistableDeclaration で取得する。
もし declarationNames に "*default*"
要素が含まれていなければ、"*default*" を declarationNames に追加する。
declarationNames を返す。
ExportDeclaration
:
export
default
ClassDeclaration
declarationNames を BoundNames の ClassDeclaration
で取得する。
もし declarationNames に "*default*"
要素が含まれていなければ、"*default*" を declarationNames に追加する。
declarationNames を返す。
ExportDeclaration
:
export
default
AssignmentExpression
;
« "*default*" » を返す。
8.2.2 静的セマンティクス:DeclarationPart
構文指向オペレーション
DeclarationPart は引数を取らず、構文ノード を返す。これは次の生成規則ごとに個別に定義される:
HoistableDeclaration
: FunctionDeclaration
FunctionDeclaration を返す。
HoistableDeclaration
: GeneratorDeclaration
GeneratorDeclaration を返す。
HoistableDeclaration
: AsyncFunctionDeclaration
AsyncFunctionDeclaration を返す。
HoistableDeclaration
: AsyncGeneratorDeclaration
AsyncGeneratorDeclaration
を返す。
Declaration : ClassDeclaration
ClassDeclaration
を返す。
Declaration : LexicalDeclaration
LexicalDeclaration を返す。
8.2.3 静的セマンティクス:IsConstantDeclaration
構文指向オペレーション
IsConstantDeclaration は引数を取らず、真偽値(Boolean)を返す。
これは次の生成規則ごとに個別に定義される:
LexicalDeclaration
:
LetOrConst
BindingList
;
IsConstantDeclaration
を LetOrConst に対して返す。
LetOrConst : let
false を返す。
LetOrConst : const
true を返す。
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
false を返す。
ClassDeclaration :
class
BindingIdentifier
ClassTail
class
ClassTail
false を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
;
export
NamedExports
;
export
default
AssignmentExpression
;
false を返す。
注
export default AssignmentExpression
を定数宣言として扱う必要はない。なぜなら、モジュールのデフォルトオブジェクトを参照するために使用される内部結合名に代入する構文は存在しないからである。
8.2.4 静的セマンティクス:LexicallyDeclaredNames
構文指向オペレーション
LexicallyDeclaredNames は引数を取らず、文字列のリスト を返す。これは次の生成規則ごとに個別に定義される。
Block :
{
}
新しい空のリスト を返す。
StatementList :
StatementList
StatementListItem
names1 を LexicallyDeclaredNames
の StatementList
で取得する。
names2 を LexicallyDeclaredNames
の StatementListItem で取得する。
names1 と names2 の リスト連結 を返す。
StatementListItem
: Statement
もし Statement が
Statement :
LabelledStatement
の場合、LexicallyDeclaredNames
の LabelledStatement を返す。
新しい空のリスト を返す。
StatementListItem
: Declaration
BoundNames を Declaration に対して返す。
CaseBlock :
{
}
新しい空のリスト を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、names1 を LexicallyDeclaredNames
の最初の CaseClauses で取得する。
そうでなければ、names1 を新しい空のリスト とする。
names2 を LexicallyDeclaredNames
の DefaultClause
で取得する。
2番目の CaseClauses
が存在する場合、names3 を LexicallyDeclaredNames
の2番目の CaseClauses
で取得する。
そうでなければ、names3 を新しい空のリスト とする。
names1 、names2 、names3 の リスト連結 を返す。
CaseClauses :
CaseClauses
CaseClause
names1 を LexicallyDeclaredNames
の CaseClauses で取得する。
names2 を LexicallyDeclaredNames
の CaseClause で取得する。
names1 と names2 の リスト連結 を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、LexicallyDeclaredNames
の StatementList を返す。
新しい空のリスト を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、LexicallyDeclaredNames
の StatementList を返す。
新しい空のリスト を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
LexicallyDeclaredNames
を LabelledItem に対して返す。
LabelledItem : Statement
新しい空のリスト を返す。
LabelledItem : FunctionDeclaration
BoundNames を FunctionDeclaration
に対して返す。
FunctionStatementList
: [空]
新しい空のリスト を返す。
FunctionStatementList
: StatementList
TopLevelLexicallyDeclaredNames
を StatementList
に対して返す。
ClassStaticBlockStatementList
: [空]
新しい空のリスト を返す。
ClassStaticBlockStatementList
: StatementList
TopLevelLexicallyDeclaredNames
を StatementList
に対して返す。
ConciseBody : ExpressionBody
新しい空のリスト を返す。
AsyncConciseBody :
ExpressionBody
新しい空のリスト を返す。
Script : [空]
新しい空のリスト を返す。
ScriptBody : StatementList
TopLevelLexicallyDeclaredNames
を StatementList
に対して返す。
注1
Script
のトップレベルでは、関数宣言はレキシカル宣言ではなく var 宣言として扱われる。
注2
Module の
LexicallyDeclaredNames には、すべてのインポート束縛の名前も含まれる。
ModuleItemList :
ModuleItemList
ModuleItem
names1 を LexicallyDeclaredNames
の ModuleItemList
で取得する。
names2 を LexicallyDeclaredNames
の ModuleItem で取得する。
names1 と names2 の リスト連結 を返す。
ModuleItem : ImportDeclaration
BoundNames を ImportDeclaration
に対して返す。
ModuleItem : ExportDeclaration
ExportDeclaration
が
export VariableStatement の場合、新しい空のリスト を返す。
BoundNames を ExportDeclaration
に対して返す。
ModuleItem : StatementListItem
LexicallyDeclaredNames
を StatementListItem に対して返す。
注3
Module のトップレベルでは、関数宣言は var
宣言ではなくレキシカル宣言として扱われる。
8.2.5 静的セマンティクス:LexicallyScopedDeclarations
構文指向オペレーション
LexicallyScopedDeclarations は引数を取らず、リスト (要素は
構文ノード )を返す。これは次の生成規則ごとに個別に定義される。
StatementList :
StatementList
StatementListItem
declarations1 を LexicallyScopedDeclarations
の StatementList
で取得する。
declarations2 を LexicallyScopedDeclarations
の StatementListItem で取得する。
declarations1 と declarations2 の リスト連結 を返す。
StatementListItem
: Statement
もし Statement が
Statement :
LabelledStatement
の場合、LexicallyScopedDeclarations
の LabelledStatement を返す。
新しい空のリスト を返す。
StatementListItem
: Declaration
リスト (唯一の要素は
DeclarationPart of
Declaration )を返す。
CaseBlock :
{
}
新しい空のリスト を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、declarations1 を LexicallyScopedDeclarations
の最初の CaseClauses で取得する。
そうでなければ、declarations1 を新しい空のリスト とする。
declarations2 を LexicallyScopedDeclarations
の DefaultClause
で取得する。
2番目の CaseClauses
が存在する場合、declarations3 を LexicallyScopedDeclarations
の2番目の CaseClauses
で取得する。
そうでなければ、declarations3 を新しい空のリスト とする。
declarations1 、declarations2 、declarations3 の リスト連結 を返す。
CaseClauses :
CaseClauses
CaseClause
declarations1 を LexicallyScopedDeclarations
の CaseClauses で取得する。
declarations2 を LexicallyScopedDeclarations
の CaseClause で取得する。
declarations1 と declarations2 の リスト連結 を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、LexicallyScopedDeclarations
の StatementList を返す。
新しい空のリスト を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、LexicallyScopedDeclarations
の StatementList を返す。
新しい空のリスト を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
LexicallyScopedDeclarations
を LabelledItem に対して返す。
LabelledItem : Statement
新しい空のリスト を返す。
LabelledItem : FunctionDeclaration
« FunctionDeclaration » を返す。
FunctionStatementList
: [空]
新しい空のリスト を返す。
FunctionStatementList
: StatementList
TopLevelLexicallyScopedDeclarations
を StatementList
に対して返す。
ClassStaticBlockStatementList
: [空]
新しい空のリスト を返す。
ClassStaticBlockStatementList
: StatementList
TopLevelLexicallyScopedDeclarations
を StatementList
に対して返す。
ConciseBody : ExpressionBody
新しい空のリスト を返す。
AsyncConciseBody :
ExpressionBody
新しい空のリスト を返す。
Script : [空]
新しい空のリスト を返す。
ScriptBody : StatementList
TopLevelLexicallyScopedDeclarations
を StatementList
に対して返す。
Module : [空]
新しい空のリスト を返す。
ModuleItemList :
ModuleItemList
ModuleItem
declarations1 を LexicallyScopedDeclarations
の ModuleItemList
で取得する。
declarations2 を LexicallyScopedDeclarations
の ModuleItem で取得する。
declarations1 と declarations2 の リスト連結 を返す。
ModuleItem : ImportDeclaration
新しい空のリスト を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
export
VariableStatement
新しい空のリスト を返す。
ExportDeclaration
:
export
Declaration
リスト (唯一の要素は
DeclarationPart of
Declaration )を返す。
ExportDeclaration
:
export
default
HoistableDeclaration
リスト (唯一の要素は
DeclarationPart of
HoistableDeclaration )を返す。
ExportDeclaration
:
export
default
ClassDeclaration
リスト (唯一の要素は ClassDeclaration )を返す。
ExportDeclaration
:
export
default
AssignmentExpression
;
リスト (唯一の要素はこの
ExportDeclaration )を返す。
8.2.6 静的セマンティクス:VarDeclaredNames
構文指向オペレーション
VarDeclaredNames は引数を取らず、文字列のリスト を返す。これは次の生成規則ごとに個別に定義される:
Statement :
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement
新しい空のリスト を返す。
Block :
{
}
新しい空のリスト を返す。
StatementList :
StatementList
StatementListItem
names1 を VarDeclaredNames の
StatementList で取得する。
names2 を VarDeclaredNames の
StatementListItem
で取得する。
names1 と names2 の リスト連結 を返す。
StatementListItem
: Declaration
新しい空のリスト を返す。
VariableStatement
:
var
VariableDeclarationList
;
BoundNames を VariableDeclarationList
に対して返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
names1 を VarDeclaredNames の
最初の Statement で取得する。
names2 を VarDeclaredNames の
2番目の Statement で取得する。
names1 と names2 の リスト連結 を返す。
IfStatement :
if
(
Expression
)
Statement
VarDeclaredNames を
Statement に対して返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
VarDeclaredNames を
Statement に対して返す。
WhileStatement :
while
(
Expression
)
Statement
VarDeclaredNames を
Statement に対して返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
VarDeclaredNames を
Statement に対して返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
names1 を BoundNames の VariableDeclarationList で取得する。
names2 を VarDeclaredNames の
Statement で取得する。
names1 と names2 の リスト連結 を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
VarDeclaredNames を
Statement に対して返す。
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
VarDeclaredNames を
Statement に対して返す。
ForInOfStatement :
for
(
var
ForBinding
in
Expression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
names1 を BoundNames の ForBinding で取得する。
names2 を VarDeclaredNames の
Statement で取得する。
names1 と names2 の リスト連結 を返す。
注
このセクションは付録 B.3.5
によって拡張される。
WithStatement :
with
(
Expression
)
Statement
VarDeclaredNames を
Statement に対して返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
VarDeclaredNames を
CaseBlock に対して返す。
CaseBlock :
{
}
新しい空のリスト を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、names1 を VarDeclaredNames の
最初の CaseClauses で取得する。
そうでなければ、names1 を新しい空のリスト とする。
names2 を VarDeclaredNames の
DefaultClause で取得する。
2番目の CaseClauses
が存在する場合、names3 を VarDeclaredNames の
2番目の CaseClauses で取得する。
そうでなければ、names3 を新しい空のリスト とする。
names1 、names2 、names3 の リスト連結 を返す。
CaseClauses :
CaseClauses
CaseClause
names1 を VarDeclaredNames の
CaseClauses で取得する。
names2 を VarDeclaredNames の
CaseClause で取得する。
names1 と names2 の リスト連結 を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、VarDeclaredNames を
StatementList に対して返す。
新しい空のリスト を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、VarDeclaredNames を
StatementList に対して返す。
新しい空のリスト を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
VarDeclaredNames を
LabelledItem に対して返す。
LabelledItem : FunctionDeclaration
新しい空のリスト を返す。
TryStatement :
try
Block
Catch
names1 を VarDeclaredNames の
Block で取得する。
names2 を VarDeclaredNames の
Catch で取得する。
names1 と names2 の リスト連結 を返す。
TryStatement :
try
Block
Finally
names1 を VarDeclaredNames の
Block で取得する。
names2 を VarDeclaredNames の
Finally で取得する。
names1 と names2 の リスト連結 を返す。
TryStatement :
try
Block
Catch
Finally
names1 を VarDeclaredNames の
Block で取得する。
names2 を VarDeclaredNames の
Catch で取得する。
names3 を VarDeclaredNames の
Finally で取得する。
names1 、names2 、names3 の リスト連結 を返す。
Catch :
catch
(
CatchParameter
)
Block
VarDeclaredNames を
Block に対して返す。
FunctionStatementList
: [空]
新しい空のリスト を返す。
FunctionStatementList
: StatementList
TopLevelVarDeclaredNames
を StatementList
に対して返す。
ClassStaticBlockStatementList
: [空]
新しい空のリスト を返す。
ClassStaticBlockStatementList
: StatementList
TopLevelVarDeclaredNames
を StatementList
に対して返す。
ConciseBody : ExpressionBody
新しい空のリスト を返す。
AsyncConciseBody :
ExpressionBody
新しい空のリスト を返す。
Script : [空]
新しい空のリスト を返す。
ScriptBody : StatementList
TopLevelVarDeclaredNames
を StatementList
に対して返す。
ModuleItemList :
ModuleItemList
ModuleItem
names1 を VarDeclaredNames の
ModuleItemList
で取得する。
names2 を VarDeclaredNames の
ModuleItem で取得する。
names1 と names2 の リスト連結 を返す。
ModuleItem : ImportDeclaration
新しい空のリスト を返す。
ModuleItem : ExportDeclaration
ExportDeclaration
が
export VariableStatement の場合、BoundNames を ExportDeclaration
に対して返す。
新しい空のリスト を返す。
8.2.7 静的セマンティクス:VarScopedDeclarations
構文指向オペレーション
VarScopedDeclarations は引数を取らず、リスト (要素は
構文ノード )を返す。これは次の生成規則ごとに個別に定義される。
Statement :
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement
新しい空のリスト を返す。
Block :
{
}
新しい空のリスト を返す。
StatementList :
StatementList
StatementListItem
declarations1 を VarScopedDeclarations
の StatementList
で取得する。
declarations2 を VarScopedDeclarations
の StatementListItem で取得する。
declarations1 と declarations2 の リスト連結 を返す。
StatementListItem
: Declaration
新しい空のリスト を返す。
VariableDeclarationList
: VariableDeclaration
« VariableDeclaration » を返す。
VariableDeclarationList
:
VariableDeclarationList
,
VariableDeclaration
declarations1 を VarScopedDeclarations
の VariableDeclarationList で取得する。
declarations1 と « VariableDeclaration » の
リスト連結 を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
declarations1 を VarScopedDeclarations
の最初の Statement で取得する。
declarations2 を VarScopedDeclarations
の2番目の Statement で取得する。
declarations1 と declarations2 の リスト連結 を返す。
IfStatement :
if
(
Expression
)
Statement
VarScopedDeclarations
を Statement に対して返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
VarScopedDeclarations
を Statement に対して返す。
WhileStatement :
while
(
Expression
)
Statement
VarScopedDeclarations
を Statement に対して返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
VarScopedDeclarations
を Statement に対して返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
declarations1 を VarScopedDeclarations
の VariableDeclarationList で取得する。
declarations2 を VarScopedDeclarations
の Statement で取得する。
declarations1 と declarations2 の リスト連結 を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
VarScopedDeclarations
を Statement に対して返す。
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
VarScopedDeclarations
を Statement に対して返す。
ForInOfStatement :
for
(
var
ForBinding
in
Expression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
declarations1 を « ForBinding » とする。
declarations2 を VarScopedDeclarations
の Statement で取得する。
declarations1 と declarations2 の リスト連結 を返す。
注
このセクションは付属書 B.3.5
によって拡張される。
WithStatement :
with
(
Expression
)
Statement
VarScopedDeclarations
を Statement に対して返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
VarScopedDeclarations
を CaseBlock に対して返す。
CaseBlock :
{
}
新しい空のリスト を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、declarations1 を VarScopedDeclarations
の最初の CaseClauses で取得する。
そうでなければ、declarations1 を新しい空のリスト とする。
declarations2 を VarScopedDeclarations
の DefaultClause
で取得する。
2番目の CaseClauses
が存在する場合、declarations3 を VarScopedDeclarations
の2番目の CaseClauses
で取得する。
そうでなければ、declarations3 を新しい空のリスト とする。
declarations1 、declarations2 、declarations3 の リスト連結 を返す。
CaseClauses :
CaseClauses
CaseClause
declarations1 を VarScopedDeclarations
の CaseClauses で取得する。
declarations2 を VarScopedDeclarations
の CaseClause で取得する。
declarations1 と declarations2 の リスト連結 を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、VarScopedDeclarations
の StatementList を返す。
新しい空のリスト を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、VarScopedDeclarations
の StatementList を返す。
新しい空のリスト を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
VarScopedDeclarations
を LabelledItem に対して返す。
LabelledItem : FunctionDeclaration
新しい空のリスト を返す。
TryStatement :
try
Block
Catch
declarations1 を VarScopedDeclarations
の Block で取得する。
declarations2 を VarScopedDeclarations
の Catch で取得する。
declarations1 と declarations2 の リスト連結 を返す。
TryStatement :
try
Block
Finally
declarations1 を VarScopedDeclarations
の Block で取得する。
declarations2 を VarScopedDeclarations
の Finally で取得する。
declarations1 と declarations2 の リスト連結 を返す。
TryStatement :
try
Block
Catch
Finally
declarations1 を VarScopedDeclarations
の Block で取得する。
declarations2 を VarScopedDeclarations
の Catch で取得する。
declarations3 を VarScopedDeclarations
の Finally で取得する。
declarations1 、declarations2 、declarations3 の リスト連結 を返す。
Catch :
catch
(
CatchParameter
)
Block
VarScopedDeclarations
を Block に対して返す。
FunctionStatementList
: [空]
新しい空のリスト を返す。
FunctionStatementList
: StatementList
TopLevelVarScopedDeclarations
を StatementList
に対して返す。
ClassStaticBlockStatementList
: [空]
新しい空のリスト を返す。
ClassStaticBlockStatementList
: StatementList
TopLevelVarScopedDeclarations
を StatementList
に対して返す。
ConciseBody : ExpressionBody
新しい空のリスト を返す。
AsyncConciseBody :
ExpressionBody
新しい空のリスト を返す。
Script : [空]
新しい空のリスト を返す。
ScriptBody : StatementList
TopLevelVarScopedDeclarations
を StatementList
に対して返す。
Module : [空]
新しい空のリスト を返す。
ModuleItemList :
ModuleItemList
ModuleItem
declarations1 を VarScopedDeclarations
の ModuleItemList
で取得する。
declarations2 を VarScopedDeclarations
の ModuleItem で取得する。
declarations1 と declarations2 の リスト連結 を返す。
ModuleItem : ImportDeclaration
新しい空のリスト を返す。
ModuleItem : ExportDeclaration
ExportDeclaration
が
export VariableStatement の場合、VarScopedDeclarations
を VariableStatement に対して返す。
新しい空のリスト を返す。
8.2.8 静的セマンティクス:TopLevelLexicallyDeclaredNames
構文指向オペレーション
TopLevelLexicallyDeclaredNamesは引数を取らず、
文字列のリスト を返す。それは次の生成規則ごとに定義される:
StatementList :
StatementList
StatementListItem
names1 を、TopLevelLexicallyDeclaredNames の
StatementList に対する値とする。
names2 を、TopLevelLexicallyDeclaredNames の
StatementListItem に対する値とする。
リスト連結 で
names1 とnames2 を返す。
StatementListItem
: Statement
新しい空のリスト を返す。
StatementListItem
: Declaration
もしDeclaration が
Declaration
: HoistableDeclaration
ならば、
新しい空のリスト を返す。
BoundNames のDeclaration に対する値を返す。
注
関数またはスクリプトのトップレベルでは、function宣言はレキシカル宣言ではなくvar宣言として扱われる。
8.2.9 静的セマンティクス:TopLevelLexicallyScopedDeclarations
構文指向オペレーション
TopLevelLexicallyScopedDeclarationsは引数を取らず、
リスト (
構文ノード )を返す。それは次の生成規則ごとに定義される:
StatementList :
StatementList
StatementListItem
declarations1 を、TopLevelLexicallyScopedDeclarations の
StatementList に対する値とする。
declarations2 を、TopLevelLexicallyScopedDeclarations の
StatementListItem に対する値とする。
リスト連結 で
declarations1 とdeclarations2 を返す。
StatementListItem
: Statement
新しい空のリスト を返す。
StatementListItem
: Declaration
もしDeclaration が
Declaration
: HoistableDeclaration
ならば、
新しい空のリスト を返す。
« Declaration »
を返す。
8.2.10 静的セマンティクス:TopLevelVarDeclaredNames
構文指向オペレーション
TopLevelVarDeclaredNamesは引数を取らず、
文字列のリスト を返す。それは次の生成規則ごとに定義される:
StatementList :
StatementList
StatementListItem
names1 を、TopLevelVarDeclaredNames の
StatementList に対する値とする。
names2 を、TopLevelVarDeclaredNames の
StatementListItem に対する値とする。
リスト連結 で
names1 とnames2 を返す。
StatementListItem
: Declaration
もしDeclaration が
Declaration
: HoistableDeclaration
ならば、
BoundNames の
HoistableDeclaration に対する値を返す。
新しい空のリスト を返す。
StatementListItem
: Statement
もしStatement が
Statement :
LabelledStatement
ならば、TopLevelVarDeclaredNames の
Statement に対する値を返す。
VarDeclaredNames の
Statement に対する値を返す。
注
関数やスクリプトのトップレベルでは、内部のfunction宣言はvar宣言として扱われる。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
TopLevelVarDeclaredNames の
LabelledItem に対する値を返す。
LabelledItem : Statement
もしStatement が
Statement :
LabelledStatement
ならば、TopLevelVarDeclaredNames の
Statement に対する値を返す。
VarDeclaredNames の
Statement に対する値を返す。
LabelledItem : FunctionDeclaration
BoundNames のFunctionDeclaration に対する値を返す。
8.2.11 静的セマンティクス:TopLevelVarScopedDeclarations
構文指向オペレーション
TopLevelVarScopedDeclarationsは引数を取らず、
リスト (構文ノード )を返す。それは次の生成規則ごとに定義される:
StatementList :
StatementList
StatementListItem
declarations1 を、TopLevelVarScopedDeclarations の
StatementList に対する値とする。
declarations2 を、TopLevelVarScopedDeclarations の
StatementListItem に対する値とする。
リスト連結 で
declarations1 とdeclarations2 を返す。
StatementListItem
: Statement
もしStatement が
Statement :
LabelledStatement
ならば、TopLevelVarScopedDeclarations の
Statement に対する値を返す。
VarScopedDeclarations の
Statement に対する値を返す。
StatementListItem
: Declaration
もしDeclaration が
Declaration
: HoistableDeclaration
ならば、
declaration をDeclarationPart の
HoistableDeclaration に対する値とする。
« declaration » を返す。
新しい空のリスト を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
TopLevelVarScopedDeclarations の
LabelledItem に対する値を返す。
LabelledItem : Statement
もしStatement が
Statement :
LabelledStatement
ならば、TopLevelVarScopedDeclarations の
Statement に対する値を返す。
VarScopedDeclarations の
Statement に対する値を返す。
LabelledItem : FunctionDeclaration
« FunctionDeclaration » を返す。
8.3 ラベル
8.3.1 静的セマンティクス:ContainsDuplicateLabels
構文指向オペレーション
ContainsDuplicateLabelsは引数labelSet (
文字列のリスト )を取り、ブール値を返す。これは以下の生成規則ごとに定義される:
Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement
Block :
{
}
StatementListItem
:
Declaration
false を返す。
StatementList :
StatementList
StatementListItem
hasDuplicates をContainsDuplicateLabels
のStatementList にlabelSet を引数として適用した結果とする。
もしhasDuplicates がtrue なら、true を返す。
ContainsDuplicateLabels
のStatementListItem にlabelSet を引数として適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasDuplicate を、最初のStatement にlabelSet を引数として
ContainsDuplicateLabels
を適用した結果とする。
もしhasDuplicate がtrue なら、true を返す。
2番目のStatement にlabelSet を引数として
ContainsDuplicateLabels
を適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
ContainsDuplicateLabels
をStatement にlabelSet を引数として適用した結果を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
ContainsDuplicateLabels
をStatement にlabelSet を引数として適用した結果を返す。
WhileStatement :
while
(
Expression
)
Statement
ContainsDuplicateLabels
をStatement にlabelSet を引数として適用した結果を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
ContainsDuplicateLabels
をStatement にlabelSet を引数として適用した結果を返す。
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
ContainsDuplicateLabels
のStatement にlabelSet を引数として適用した結果を返す。
注
このセクションは付録B.3.5 によって拡張されている。
WithStatement :
with
(
Expression
)
Statement
ContainsDuplicateLabels
をStatement にlabelSet を引数として適用した結果を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
ContainsDuplicateLabels
をCaseBlock にlabelSet を引数として適用した結果を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初のCaseClauses が存在する場合、
最初のCaseClauses にlabelSet を引数として
ContainsDuplicateLabels
を適用した結果がtrue なら、true を返す。
DefaultClause にlabelSet を引数として
ContainsDuplicateLabels
を適用した結果がtrue なら、true を返す。
2番目のCaseClauses が存在しなければ、false を返す。
2番目のCaseClauses にlabelSet を引数として
ContainsDuplicateLabels
を適用した結果を返す。
CaseClauses :
CaseClauses
CaseClause
hasDuplicates をContainsDuplicateLabels
のCaseClauses にlabelSet を引数として適用した結果とする。
もしhasDuplicates がtrue なら、true を返す。
ContainsDuplicateLabels
をCaseClause にlabelSet を引数として適用した結果を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList が存在する場合、
ContainsDuplicateLabels
をStatementList にlabelSet を引数として適用した結果を返す。
false を返す。
DefaultClause :
default
:
StatementList opt
StatementList が存在する場合、
ContainsDuplicateLabels
をStatementList にlabelSet を引数として適用した結果を返す。
false を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
label をLabelIdentifier のStringValue とする。
もしlabelSet がlabel を含むなら、true を返す。
newLabelSet をlist-concatenation によりlabelSet と«
label »の連結とする。
ContainsDuplicateLabels
をLabelledItem にnewLabelSet を引数として適用した結果を返す。
ラベル付き項目 : 関数宣言
false を返す。
try文 :
try
ブロック
catch節
hasDuplicates に ContainsDuplicateLabels
の ブロック と引数
labelSet を設定する。
hasDuplicates が true の場合、true を返す。
ContainsDuplicateLabels
の catch節 と引数
labelSet を返す。
try文 :
try
ブロック
finally節
hasDuplicates に ContainsDuplicateLabels
の ブロック と引数
labelSet を設定する。
hasDuplicates が true の場合、true を返す。
ContainsDuplicateLabels
の finally節 と引数
labelSet を返す。
try文 :
try
ブロック
catch節
finally節
ContainsDuplicateLabels
の ブロック と引数
labelSet が true の場合、true を返す。
ContainsDuplicateLabels
の catch節 と引数
labelSet が true の場合、true を返す。
ContainsDuplicateLabels
の finally節 と引数
labelSet を返す。
catch節 :
catch
(
catchパラメータ
)
ブロック
ContainsDuplicateLabels
の ブロック と引数
labelSet を返す。
関数ステートメントリスト
: [空]
false を返す。
クラス静的ブロックステートメントリスト
: [空]
false を返す。
モジュール項目リスト :
モジュール項目リスト
モジュール項目
hasDuplicates に ContainsDuplicateLabels
の モジュール項目リスト
と引数 labelSet を設定する。
hasDuplicates が true の場合、true を返す。
ContainsDuplicateLabels
の モジュール項目 と引数
labelSet を返す。
モジュール項目 :
インポート宣言
エクスポート宣言
false を返す。
8.3.2 静的セマンティクス: ContainsUndefinedBreakTarget
構文指向オペレーション
ContainsUndefinedBreakTarget は引数 labelSet (文字列のリスト )を取り、Boolean
を返す。これは以下の生成規則ごとに定義される:
Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
ReturnStatement
ThrowStatement
DebuggerStatement
Block :
{
}
StatementListItem
:
Declaration
false を返す。
StatementList :
StatementList
StatementListItem
hasUndefinedLabels に ContainsUndefinedBreakTarget
of StatementList を引数
labelSet で適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedBreakTarget
of StatementListItem を引数
labelSet で適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasUndefinedLabels に、最初の Statement に labelSet を渡して
ContainsUndefinedBreakTarget
を適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
2つ目の Statement に
labelSet を渡して ContainsUndefinedBreakTarget
を適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
WhileStatement :
while
(
Expression
)
Statement
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
補足
BreakStatement :
break
;
false を返す。
BreakStatement :
break
LabelIdentifier
;
もし labelSet に LabelIdentifier の
StringValue
が含まれていなければ、true を返す。
false を返す。
WithStatement :
with
(
Expression
)
Statement
ContainsUndefinedBreakTarget
を Statement に
labelSet を渡して適用した結果を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
ContainsUndefinedBreakTarget
を CaseBlock に
labelSet を渡して適用した結果を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、
もし ContainsUndefinedBreakTarget
of 最初の CaseClauses に labelSet
を渡して適用した結果が true なら、true を返す。
ContainsUndefinedBreakTarget
of DefaultClause に
labelSet を渡して適用した結果が true なら、true を返す。
2つ目の CaseClauses
が存在しない場合、false を返す。
ContainsUndefinedBreakTarget
of 2つ目の CaseClauses に
labelSet を渡して適用した結果を返す。
CaseClauses :
CaseClauses
CaseClause
hasUndefinedLabels に ContainsUndefinedBreakTarget
of CaseClauses に
labelSet を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedBreakTarget
of CaseClause に
labelSet を渡して適用した結果を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、ContainsUndefinedBreakTarget
of StatementList に
labelSet を渡して適用した結果を返す。
false を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、ContainsUndefinedBreakTarget
of StatementList に
labelSet を渡して適用した結果を返す。
false を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
label に LabelIdentifier の
StringValue を代入する。
newLabelSet に labelSet と « label »
のリスト連結を代入する。
ContainsUndefinedBreakTarget
を LabelledItem に
newLabelSet を渡して適用した結果を返す。
LabelledItem : FunctionDeclaration
false を返す。
TryStatement :
try
Block
Catch
hasUndefinedLabels に ContainsUndefinedBreakTarget
of Block に
labelSet を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedBreakTarget
of Catch に
labelSet を渡して適用した結果を返す。
TryStatement :
try
Block
Finally
hasUndefinedLabels に ContainsUndefinedBreakTarget
of Block に
labelSet を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedBreakTarget
of Finally に
labelSet を渡して適用した結果を返す。
TryStatement :
try
Block
Catch
Finally
ContainsUndefinedBreakTarget
of Block に
labelSet を渡して適用した結果が true なら、true を返す。
ContainsUndefinedBreakTarget
of Catch に
labelSet を渡して適用した結果が true なら、true を返す。
ContainsUndefinedBreakTarget
of Finally に
labelSet を渡して適用した結果を返す。
Catch :
catch
(
CatchParameter
)
Block
ContainsUndefinedBreakTarget
of Block に
labelSet を渡して適用した結果を返す。
FunctionStatementList
: [empty]
false を返す。
ClassStaticBlockStatementList
: [empty]
false を返す。
ModuleItemList :
ModuleItemList
ModuleItem
hasUndefinedLabels に ContainsUndefinedBreakTarget
of ModuleItemList
に labelSet を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedBreakTarget
of ModuleItem に
labelSet を渡して適用した結果を返す。
ModuleItem :
ImportDeclaration
ExportDeclaration
false を返す。
8.3.3 静的セマンティクス: ContainsUndefinedContinueTarget
構文指向オペレーション
ContainsUndefinedContinueTarget は引数 iterationSet (文字列のリスト )および
labelSet (文字列のリスト )を取り、Boolean
を返す。これは以下の生成規則ごとに定義される:
Statement :
VariableStatement
EmptyStatement
ExpressionStatement
BreakStatement
ReturnStatement
ThrowStatement
DebuggerStatement
Block :
{
}
StatementListItem
:
Declaration
false を返す。
Statement : BlockStatement
ContainsUndefinedContinueTarget
を BlockStatement に
iterationSet および « » を渡して適用した結果を返す。
BreakableStatement
: IterationStatement
newIterationSet に iterationSet と labelSet
のリスト連結を代入する。
ContainsUndefinedContinueTarget
を IterationStatement に
newIterationSet および « » を渡して適用した結果を返す。
StatementList :
StatementList
StatementListItem
hasUndefinedLabels に ContainsUndefinedContinueTarget
of StatementList に
iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedContinueTarget
of StatementListItem に
iterationSet および « » を渡して適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
hasUndefinedLabels に ContainsUndefinedContinueTarget
of 最初の Statement に
iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
2つ目の Statement に
iterationSet および « » を渡して ContainsUndefinedContinueTarget
を適用した結果を返す。
IfStatement :
if
(
Expression
)
Statement
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
DoWhileStatement :
do
Statement
while
(
Expression
)
;
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
WhileStatement :
while
(
Expression
)
Statement
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
補足
ContinueStatement
:
continue
;
false を返す。
ContinueStatement
:
continue
LabelIdentifier
;
もし iterationSet に LabelIdentifier の
StringValue
が含まれていなければ、true を返す。
false を返す。
WithStatement :
with
(
Expression
)
Statement
ContainsUndefinedContinueTarget
を Statement に
iterationSet および « » を渡して適用した結果を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
ContainsUndefinedContinueTarget
を CaseBlock に
iterationSet および « » を渡して適用した結果を返す。
CaseBlock :
{
}
false を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
最初の CaseClauses
が存在する場合、
もし ContainsUndefinedContinueTarget
of 最初の CaseClauses に
iterationSet および « » を渡して適用した結果が true
なら、true を返す。
ContainsUndefinedContinueTarget
of DefaultClause に
iterationSet および « » を渡して適用した結果が true
なら、true を返す。
2つ目の CaseClauses
が存在しない場合、false を返す。
ContainsUndefinedContinueTarget
of 2つ目の CaseClauses に
iterationSet および « » を渡して適用した結果を返す。
CaseClauses :
CaseClauses
CaseClause
hasUndefinedLabels に ContainsUndefinedContinueTarget
of CaseClauses に
iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedContinueTarget
of CaseClause に
iterationSet および « » を渡して適用した結果を返す。
CaseClause :
case
Expression
:
StatementList opt
StatementList
が存在する場合、ContainsUndefinedContinueTarget
of StatementList に
iterationSet および « » を渡して適用した結果を返す。
false を返す。
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、ContainsUndefinedContinueTarget
of StatementList に
iterationSet および « » を渡して適用した結果を返す。
false を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
label に LabelIdentifier の
StringValue を代入する。
newLabelSet に labelSet と « label »
のリスト連結を代入する。
ContainsUndefinedContinueTarget
を LabelledItem に
iterationSet および newLabelSet を渡して適用した結果を返す。
LabelledItem : FunctionDeclaration
false を返す。
TryStatement :
try
Block
Catch
hasUndefinedLabels に ContainsUndefinedContinueTarget
of Block に
iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedContinueTarget
of Catch に
iterationSet および « » を渡して適用した結果を返す。
TryStatement :
try
Block
Finally
hasUndefinedLabels に ContainsUndefinedContinueTarget
of Block に
iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedContinueTarget
of Finally に
iterationSet および « » を渡して適用した結果を返す。
TryStatement :
try
Block
Catch
Finally
ContainsUndefinedContinueTarget
of Block に
iterationSet および « » を渡して適用した結果が true
なら、true を返す。
ContainsUndefinedContinueTarget
of Catch に
iterationSet および « » を渡して適用した結果が true
なら、true を返す。
ContainsUndefinedContinueTarget
of Finally に
iterationSet および « » を渡して適用した結果を返す。
Catch :
catch
(
CatchParameter
)
Block
ContainsUndefinedContinueTarget
of Block に
iterationSet および « » を渡して適用した結果を返す。
FunctionStatementList
: [empty]
false を返す。
ClassStaticBlockStatementList
: [empty]
false を返す。
ModuleItemList :
ModuleItemList
ModuleItem
hasUndefinedLabels に ContainsUndefinedContinueTarget
of ModuleItemList
に iterationSet および « » を渡して適用した結果を代入する。
もし hasUndefinedLabels が true なら、true
を返す。
ContainsUndefinedContinueTarget
of ModuleItem に
iterationSet および « » を渡して適用した結果を返す。
ModuleItem :
ImportDeclaration
ExportDeclaration
false を返す。
8.4 関数名の推論
8.4.1 静的セマンティクス: HasName
構文指向オペレーション
HasName は引数を取らず、Boolean を返す。これは以下の生成規則ごとに定義される:
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
expr を ParenthesizedExpression (CoverParenthesizedExpressionAndArrowParameterList
によってカバーされている もの)とする。
IsFunctionDefinition
of expr が false なら、false を返す。
HasName of expr
を返す。
FunctionExpression
:
function
(
FormalParameters
)
{
FunctionBody
}
GeneratorExpression
:
function
*
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionExpression
:
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
ArrowFunction :
ArrowParameters
=>
ConciseBody
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
ClassExpression :
class
ClassTail
false を返す。
FunctionExpression
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
GeneratorExpression
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionExpression
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
ClassExpression :
class
BindingIdentifier
ClassTail
true を返す。
8.4.2 静的セマンティクス: IsFunctionDefinition
構文指向オペレーション
IsFunctionDefinition は引数を取らず、Boolean を返す。このオペレーションは、以下の生成規則ごとに定義される:
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
expr を ParenthesizedExpression (CoverParenthesizedExpressionAndArrowParameterList
によりカバーされている もの)とする。
IsFunctionDefinition
of expr を返す。
PrimaryExpression
:
this
IdentifierReference
Literal
ArrayLiteral
ObjectLiteral
RegularExpressionLiteral
TemplateLiteral
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
MemberExpression
TemplateLiteral
SuperProperty
MetaProperty
new
MemberExpression
Arguments
MemberExpression
.
PrivateIdentifier
NewExpression :
new
NewExpression
LeftHandSideExpression
:
CallExpression
OptionalExpression
UpdateExpression :
LeftHandSideExpression
++
LeftHandSideExpression
--
++
UnaryExpression
--
UnaryExpression
UnaryExpression :
delete
UnaryExpression
void
UnaryExpression
typeof
UnaryExpression
+
UnaryExpression
-
UnaryExpression
~
UnaryExpression
!
UnaryExpression
AwaitExpression
ExponentiationExpression
:
UpdateExpression
**
ExponentiationExpression
MultiplicativeExpression
:
MultiplicativeExpression
MultiplicativeOperator
ExponentiationExpression
AdditiveExpression
:
AdditiveExpression
+
MultiplicativeExpression
AdditiveExpression
-
MultiplicativeExpression
ShiftExpression :
ShiftExpression
<<
AdditiveExpression
ShiftExpression
>>
AdditiveExpression
ShiftExpression
>>>
AdditiveExpression
RelationalExpression
:
RelationalExpression
<
ShiftExpression
RelationalExpression
>
ShiftExpression
RelationalExpression
<=
ShiftExpression
RelationalExpression
>=
ShiftExpression
RelationalExpression
instanceof
ShiftExpression
RelationalExpression
in
ShiftExpression
PrivateIdentifier
in
ShiftExpression
EqualityExpression
:
EqualityExpression
==
RelationalExpression
EqualityExpression
!=
RelationalExpression
EqualityExpression
===
RelationalExpression
EqualityExpression
!==
RelationalExpression
BitwiseANDExpression
:
BitwiseANDExpression
&
EqualityExpression
BitwiseXORExpression
:
BitwiseXORExpression
^
BitwiseANDExpression
BitwiseORExpression
:
BitwiseORExpression
|
BitwiseXORExpression
LogicalANDExpression
:
LogicalANDExpression
&&
BitwiseORExpression
LogicalORExpression
:
LogicalORExpression
||
LogicalANDExpression
CoalesceExpression
:
CoalesceExpressionHead
??
BitwiseORExpression
ConditionalExpression
:
ShortCircuitExpression
?
AssignmentExpression
:
AssignmentExpression
AssignmentExpression
:
YieldExpression
LeftHandSideExpression
=
AssignmentExpression
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
LeftHandSideExpression
&&=
AssignmentExpression
LeftHandSideExpression
||=
AssignmentExpression
LeftHandSideExpression
??=
AssignmentExpression
Expression :
Expression
,
AssignmentExpression
false を返す。
AssignmentExpression
:
ArrowFunction
AsyncArrowFunction
FunctionExpression
:
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorExpression
:
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionExpression
:
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
ClassExpression :
class
BindingIdentifier opt
ClassTail
true を返す。
8.4.3 静的セマンティクス: IsAnonymousFunctionDefinition (expr )
抽象オペレーション IsAnonymousFunctionDefinition は引数 expr (AssignmentExpression 構文ノード 、Initializer 構文ノード 、または Expression 構文ノード )を取り、Boolean
を返す。このオペレーションは、引数が名前を束縛しない関数定義であるかどうかを判定する。呼び出されたとき、次の手順を実行する:
IsFunctionDefinition
of expr が false なら、false を返す。
hasName に HasName of expr
を代入する。
hasName が true なら、false を返す。
true を返す。
8.4.4 静的セマンティクス: IsIdentifierRef
構文指向オペレーション
IsIdentifierRef は引数を取らず、Boolean を返す。これは以下の生成規則ごとに定義される:
PrimaryExpression
: IdentifierReference
true を返す。
PrimaryExpression
:
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral
CoverParenthesizedExpressionAndArrowParameterList
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
MemberExpression
TemplateLiteral
SuperProperty
MetaProperty
new
MemberExpression
Arguments
MemberExpression
.
PrivateIdentifier
NewExpression :
new
NewExpression
LeftHandSideExpression
:
CallExpression
OptionalExpression
false を返す。
8.4.5 実行時セマンティクス: NamedEvaluation
構文指向オペレーション
NamedEvaluation は引数 name (プロパティキー または プライベート名 )を取り、正常完了値 (関数オブジェクト を含む)または突然の完了 を返す。これは以下の生成規則ごとに定義される:
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
expr を ParenthesizedExpression (CoverParenthesizedExpressionAndArrowParameterList
によりカバーされている もの)とする。
? NamedEvaluation of expr に引数
name を渡して返す。
ParenthesizedExpression
:
(
Expression
)
アサート : IsAnonymousFunctionDefinition (Expression ) が
true であること。
? NamedEvaluation of Expression に引数 name を渡して返す。
FunctionExpression
:
function
(
FormalParameters
)
{
FunctionBody
}
InstantiateOrdinaryFunctionExpression
of FunctionExpression に引数
name を渡して返す。
GeneratorExpression
:
function
*
(
FormalParameters
)
{
GeneratorBody
}
InstantiateGeneratorFunctionExpression
of GeneratorExpression に引数
name を渡して返す。
AsyncGeneratorExpression
:
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
InstantiateAsyncGeneratorFunctionExpression
of AsyncGeneratorExpression に引数
name を渡して返す。
AsyncFunctionExpression
:
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
InstantiateAsyncFunctionExpression
of AsyncFunctionExpression に引数
name を渡して返す。
ArrowFunction :
ArrowParameters
=>
ConciseBody
InstantiateArrowFunctionExpression
of ArrowFunction に引数
name を渡して返す。
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
InstantiateAsyncArrowFunctionExpression
of AsyncArrowFunction に引数
name を渡して返す。
ClassExpression :
class
ClassTail
value に ? ClassDefinitionEvaluation of ClassTail に引数
undefined と name を渡して返す。
value .[[SourceText]] に ClassExpression
にマッチしたソーステキストを設定する。
value を返す。
8.5 含む
8.5.1 静的セマンティクス: Contains
構文指向オペレーション
Containsは引数symbol (文法記号)を取り、Booleanを返す。
本仕様において、以下に列挙されていないすべての文法生成規則の選択肢は、暗黙的に次のデフォルトのContains定義を持つ:
この構文ノード の各子ノードchild について、以下を実行する:
もしchild がsymbol のインスタンスであれば、true を返す。
もしchild が非終端記号のインスタンスであれば、
contained をchild Contains
symbol の結果とする。
もしcontained がtrue であれば、true を返す。
false を返す。
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression
:
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression
:
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
false を返す。
注 1
サブ構造に依存する静的セマンティクス規則は、一般的に関数定義の内部は調べない。
ClassTail :
ClassHeritage opt
{
ClassBody
}
もしsymbol がClassBody であれば、true を返す。
もしsymbol がClassHeritage であれば、
もしClassHeritage が存在すればtrue 、そうでなければfalse を返す。
もしClassHeritage が存在すれば、
もしClassHeritage Contains
symbol がtrue であれば、true を返す。
ComputedPropertyContains
をClassBody と引数symbol で呼び出した結果を返す。
注 2
サブ構造に依存する静的セマンティクス規則は、一般的にクラス本体の内部はPropertyName 以外は調べない。
ClassStaticBlock :
static
{
ClassStaticBlockBody
}
false を返す。
注 3
サブ構造に依存する静的セマンティクス規則は、一般的にstatic 初期化ブロックの内部は調べない。
ArrowFunction :
ArrowParameters
=>
ConciseBody
もしsymbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもなければ、false を返す。
もしArrowParameters
Contains symbol
がtrue であれば、true を返す。
ConciseBody
Contains
symbol の結果を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals をArrowFormalParameters とし、それは被覆 されているCoverParenthesizedExpressionAndArrowParameterList に対応する。
formals Contains
symbol の結果を返す。
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
もしsymbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもなければ、false を返す。
AsyncConciseBody
Contains
symbol の結果を返す。
AsyncArrowFunction
:
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
もしsymbol がNewTarget 、SuperProperty 、SuperCall 、super、またはthisのいずれでもなければ、false を返す。
head をAsyncArrowHead とし、それは被覆 されているCoverCallExpressionAndAsyncArrowHead に対応する。
もしhead Contains symbol
がtrue であれば、true を返す。
AsyncConciseBody
Contains
symbol の結果を返す。
注 4
ContainsはArrowFunction またはAsyncArrowFunction 内でnew.target、this、およびsuperの使用を検出するために利用される。
PropertyDefinition
: MethodDefinition
もしsymbol がMethodDefinition であれば、true を返す。
ComputedPropertyContains
をMethodDefinition と引数symbol で呼び出した結果を返す。
LiteralPropertyName
: IdentifierName
false を返す。
MemberExpression :
MemberExpression
.
IdentifierName
もしMemberExpression
Contains symbol
がtrue であれば、true を返す。
false を返す。
SuperProperty :
super
.
IdentifierName
もしsymbol がReservedWord
superであれば、true を返す。
false を返す。
CallExpression :
CallExpression
.
IdentifierName
もしCallExpression
Contains symbol
がtrue であれば、true を返す。
false を返す。
OptionalChain :
?.
IdentifierName
false を返す。
OptionalChain :
OptionalChain
.
IdentifierName
もしOptionalChain
Contains symbol
がtrue であれば、true を返す。
false を返す。
8.5.2 静的セマンティクス: ComputedPropertyContains
構文指向オペレーション
ComputedPropertyContainsは引数symbol (文法記号)を取り、Booleanを返す。このオペレーションは、次の生成規則ごとに定義される:
ClassElementName :
PrivateIdentifier
PropertyName : LiteralPropertyName
false を返す。
PropertyName : ComputedPropertyName
ComputedPropertyName Contains
symbol の結果を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
ComputedPropertyContains
をClassElementName と引数symbol で呼び出した結果を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
ComputedPropertyContains
をClassElementName と引数symbol で呼び出した結果を返す。
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
ComputedPropertyContains
をClassElementName と引数symbol で呼び出した結果を返す。
ClassElementList :
ClassElementList
ClassElement
inList をComputedPropertyContains
をClassElementList と引数symbol で呼び出した結果とする。
もしinList がtrue であれば、true を返す。
ComputedPropertyContains
をClassElement と引数symbol で呼び出した結果を返す。
ClassElement : ClassStaticBlock
false を返す。
ClassElement : ;
false を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
ComputedPropertyContains
をClassElementName と引数symbol で呼び出した結果を返す。
FieldDefinition :
ClassElementName
Initializer opt
ComputedPropertyContains
をClassElementName と引数symbol で呼び出した結果を返す。
8.6 その他
これらの操作は、仕様書の複数の箇所で使用されます。
8.6.1 実行時セマンティクス: InstantiateFunctionObject
構文指向操作
InstantiateFunctionObject は、引数 env (
Environment Record
)および privateEnv (
PrivateEnvironment Record
または null )を取り、ECMAScript
関数オブジェクト
を返します。これは、以下の生成規則ごとに定義されます:
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
InstantiateOrdinaryFunctionObject
を FunctionDeclaration 、引数
env および privateEnv で呼び出した結果を返す。
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
InstantiateGeneratorFunctionObject
を GeneratorDeclaration 、引数
env および privateEnv で呼び出した結果を返す。
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
InstantiateAsyncGeneratorFunctionObject
を AsyncGeneratorDeclaration 、引数
env および privateEnv で呼び出した結果を返す。
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
InstantiateAsyncFunctionObject
を AsyncFunctionDeclaration 、引数
env および privateEnv で呼び出した結果を返す。
8.6.2 実行時セマンティクス: BindingInitialization
構文指向操作
BindingInitialization は、引数 value (
ECMAScript 言語値 )および
environment (
Environment Record または
undefined )を取り、unused
を含む正常完了
または 突然の完了
のいずれかを返す。
注
environment に undefined が渡される場合、
初期化値の代入には
PutValue
操作が使用されることを示す。これは var 文や一部の
非厳格関数
の仮引数リストの場合である(10.2.11 を参照)。
これらの場合、レキシカルバインディングが巻き上げられ、初期化子の評価前に事前初期化される。
これは以下の生成規則ごとに定義される:
BindingIdentifier
: Identifier
name を StringValue
(Identifier の)とする。
InitializeBoundName (name ,
value , environment )
を実行し、その結果を返す(?付き)。
BindingIdentifier
: yield
InitializeBoundName ("yield" ,
value , environment )
を実行し、その結果を返す(?付き)。
BindingIdentifier
: await
InitializeBoundName ("await" ,
value , environment )
を実行し、その結果を返す(?付き)。
BindingPattern :
ObjectBindingPattern
? RequireObjectCoercible (value )
を実行する。
BindingInitialization of ObjectBindingPattern (引数
value と environment )
を実行し、その結果を返す(?付き)。
BindingPattern :
ArrayBindingPattern
iteratorRecord を
? GetIterator (value ,
sync )
とする。
result を
Completion (
IteratorBindingInitialization of ArrayBindingPattern
(引数 iteratorRecord と environment ))
とする。
iteratorRecord .[[Done]] が
false の場合、? IteratorClose (iteratorRecord ,
result )
を返す。
? result を返す。
ObjectBindingPattern
:
{
}
unused を返す。
ObjectBindingPattern
:
{
BindingPropertyList
}
{
BindingPropertyList
,
}
? PropertyBindingInitialization of BindingPropertyList
(引数 value と environment )を実行する。
unused を返す。
ObjectBindingPattern
:
{
BindingRestProperty
}
excludedNames を新しい空の
List
とする。
RestBindingInitialization of BindingRestProperty
(引数 value , environment , excludedNames )
を実行し、その結果を返す(?付き)。
ObjectBindingPattern
:
{
BindingPropertyList
,
BindingRestProperty
}
excludedNames を
? PropertyBindingInitialization of BindingPropertyList
(引数 value と environment )の結果とする。
RestBindingInitialization of BindingRestProperty
(引数 value , environment , excludedNames )
を実行し、その結果を返す(?付き)。
8.6.2.1 InitializeBoundName ( name , value ,
environment )
抽象操作 InitializeBoundName は、引数 name (文字列)、value (
ECMAScript
言語値 )、environment (
Environment Record または
undefined )を取り、unused
を含む正常完了
または 突然の完了 のいずれかを返す。
呼び出されたとき、次の手順を実行する:
environment が undefined でない場合、
! environment .InitializeBinding(name ,
value ) を実行する。
unused を返す。
それ以外の場合、
lhs を
? ResolveBinding (name )
とする。
? PutValue (lhs ,
value )
を返す。
8.6.3 実行時セマンティクス: IteratorBindingInitialization
構文指向操作
IteratorBindingInitialization は、iteratorRecord (
Iterator
Record
)および environment (
Environment Record または
undefined )を引数として取り、
unused を含む正常完了
または
突然の完了
のいずれかを返す。
注
environment に undefined が渡された場合、それは初期化値の代入に
PutValue
操作を使用することを示す。これは
非厳格関数
の仮引数リストの場合であり、この場合、同じ名前の複数パラメータの可能性に対応するため、仮引数バインディングは事前初期化される。
これは以下の生成規則ごとに定義される:
ArrayBindingPattern
:
[
]
unused を返す。
ArrayBindingPattern
:
[
Elision
]
? IteratorDestructuringAssignmentEvaluation
of Elision (引数
iteratorRecord )
を実行し、その結果を返す。
ArrayBindingPattern
:
[
Elision opt
BindingRestElement
]
Elision が存在する場合、
? IteratorDestructuringAssignmentEvaluation
of Elision (引数
iteratorRecord )
を実行する。
? IteratorBindingInitialization of BindingRestElement
(引数 iteratorRecord および environment )を実行し、その結果を返す。
ArrayBindingPattern
:
[
BindingElementList
,
Elision
]
? IteratorBindingInitialization of BindingElementList
(引数 iteratorRecord および environment )を実行する。
? IteratorDestructuringAssignmentEvaluation
of Elision (引数
iteratorRecord )
を実行し、その結果を返す。
ArrayBindingPattern
:
[
BindingElementList
,
Elision opt
BindingRestElement
]
? IteratorBindingInitialization of BindingElementList
(引数 iteratorRecord および environment )を実行する。
Elision が存在する場合、
? IteratorDestructuringAssignmentEvaluation
of Elision (引数
iteratorRecord )
を実行する。
? IteratorBindingInitialization of BindingRestElement
(引数 iteratorRecord および environment )を実行し、その結果を返す。
BindingElementList
:
BindingElementList
,
BindingElisionElement
? IteratorBindingInitialization of BindingElementList
(引数 iteratorRecord および environment )を実行する。
? IteratorBindingInitialization of BindingElisionElement
(引数 iteratorRecord および environment )を実行し、その結果を返す。
BindingElisionElement
:
Elision
BindingElement
? IteratorDestructuringAssignmentEvaluation
of Elision (引数
iteratorRecord )
を実行する。
? IteratorBindingInitialization of BindingElement
(引数 iteratorRecord および environment )を実行し、その結果を返す。
SingleNameBinding
:
BindingIdentifier
Initializer opt
bindingId を StringValue
of BindingIdentifier
とする。
lhs を
? ResolveBinding (bindingId ,
environment )
とする。
v を undefined とする。
iteratorRecord .[[Done]] が false
の場合、
next を
? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
v に next を設定する。
Initializer が存在し、
v が undefined の場合、
IsAnonymousFunctionDefinition
(Initializer )
が true の場合、
v に
? NamedEvaluation
of Initializer
(引数 bindingId )の結果を設定する。
それ以外の場合、
defaultValue を
? Evaluation
of Initializer の結果とする。
v に
? GetValue (defaultValue )
の結果を設定する。
environment が undefined の場合、
? PutValue (lhs , v )
を返す。
? InitializeReferencedBinding (lhs ,
v ) を返す。
BindingElement :
BindingPattern
Initializer opt
v を undefined とする。
iteratorRecord .[[Done]] が false
の場合、
next を
? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
v に next を設定する。
Initializer が存在し、
v が undefined の場合、
defaultValue を
? Evaluation
of Initializer
の結果とする。
v に
? GetValue (defaultValue )
の結果を設定する。
? BindingInitialization of BindingPattern
(引数 v および environment )を実行し、その結果を返す。
BindingRestElement
:
...
BindingIdentifier
lhs を
? ResolveBinding (StringValue of BindingIdentifier ,
environment )
とする。
A を
! ArrayCreate (0)
とする。
n を 0 とする。
繰り返し、
next を done とする。
iteratorRecord .[[Done]] が
false の場合、
next に
? IteratorStepValue (iteratorRecord )
を設定する。
next が done の場合、
environment が undefined なら
? PutValue (lhs ,
A )
を返す。
? InitializeReferencedBinding (lhs ,
A )
を返す。
! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
next )
を実行する。
n を n + 1 に設定する。
BindingRestElement
:
...
BindingPattern
A を
! ArrayCreate (0)
とする。
n を 0 とする。
繰り返し、
next を done とする。
iteratorRecord .[[Done]] が
false の場合、
next に
? IteratorStepValue (iteratorRecord )
を設定する。
next が done の場合、
? BindingInitialization
of BindingPattern
(引数 A および environment )を実行し、その結果を返す。
! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
next )
を実行する。
n を n + 1 に設定する。
FormalParameters :
[empty]
unused を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
? IteratorBindingInitialization of FormalParameterList
(引数 iteratorRecord および environment )を実行する。
? IteratorBindingInitialization of FunctionRestParameter
(引数 iteratorRecord および environment )を実行し、その結果を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
? IteratorBindingInitialization of FormalParameterList
(引数 iteratorRecord および environment )を実行する。
? IteratorBindingInitialization of FormalParameter
(引数 iteratorRecord および environment )を実行し、その結果を返す。
ArrowParameters :
BindingIdentifier
v を undefined とする。
Assert :
iteratorRecord .[[Done]] は false
である。
next を
? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
v に next を設定する。
? BindingInitialization of BindingIdentifier
(引数 v および environment )を実行し、その結果を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals を ArrowFormalParameters
(CoverParenthesizedExpressionAndArrowParameterList
により cover される)とする。
? IteratorBindingInitialization of
formals (引数 iteratorRecord および environment )を実行し、その結果を返す。
AsyncArrowBindingIdentifier
: BindingIdentifier
v を undefined とする。
Assert :
iteratorRecord .[[Done]] は false
である。
next を
? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
v に next を設定する。
? BindingInitialization of BindingIdentifier
(引数 v および environment )を実行し、その結果を返す。
8.6.4 静的セマンティクス: AssignmentTargetType
構文指向操作
AssignmentTargetType は引数を取らず、simple 、web-compat 、または
invalid を返す。これは以下の生成規則ごとに定義される:
IdentifierReference
: Identifier
IsStrict (この IdentifierReference )
が true であり、かつ StringValue
of Identifier
が "eval" または "arguments"
のいずれかである場合、invalid を返す。
simple を返す。
IdentifierReference
:
yield
await
CallExpression :
CallExpression
[
Expression
]
CallExpression
.
IdentifierName
CallExpression
.
PrivateIdentifier
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
SuperProperty
MemberExpression
.
PrivateIdentifier
simple を返す。
PrimaryExpression
:
CoverParenthesizedExpressionAndArrowParameterList
expr を ParenthesizedExpression
(CoverParenthesizedExpressionAndArrowParameterList
により cover されたもの)とする。
expr の AssignmentTargetType
を返す。
CallExpression :
CoverCallExpressionAndAsyncArrowHead
CallExpression
Arguments
ホスト
がウェブブラウザーであるか、または 関数呼び出し代入ターゲットの実行時エラー
をサポートしており、
IsStrict (この
CallExpression )
が false の場合、
web-compat を返す。
invalid を返す。
PrimaryExpression
:
this
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral
CallExpression :
SuperCall
ImportCall
CallExpression
TemplateLiteral
NewExpression :
new
NewExpression
MemberExpression :
MemberExpression
TemplateLiteral
new
MemberExpression
Arguments
NewTarget :
new
.
target
ImportMeta :
import
.
meta
LeftHandSideExpression
:
OptionalExpression
UpdateExpression :
LeftHandSideExpression
++
LeftHandSideExpression
--
++
UnaryExpression
--
UnaryExpression
UnaryExpression :
delete
UnaryExpression
void
UnaryExpression
typeof
UnaryExpression
+
UnaryExpression
-
UnaryExpression
~
UnaryExpression
!
UnaryExpression
AwaitExpression
ExponentiationExpression
:
UpdateExpression
**
ExponentiationExpression
MultiplicativeExpression
:
MultiplicativeExpression
MultiplicativeOperator
ExponentiationExpression
AdditiveExpression
:
AdditiveExpression
+
MultiplicativeExpression
AdditiveExpression
-
MultiplicativeExpression
ShiftExpression :
ShiftExpression
<<
AdditiveExpression
ShiftExpression
>>
AdditiveExpression
ShiftExpression
>>>
AdditiveExpression
RelationalExpression
:
RelationalExpression
<
ShiftExpression
RelationalExpression
>
ShiftExpression
RelationalExpression
<=
ShiftExpression
RelationalExpression
>=
ShiftExpression
RelationalExpression
instanceof
ShiftExpression
RelationalExpression
in
ShiftExpression
PrivateIdentifier
in
ShiftExpression
EqualityExpression
:
EqualityExpression
==
RelationalExpression
EqualityExpression
!=
RelationalExpression
EqualityExpression
===
RelationalExpression
EqualityExpression
!==
RelationalExpression
BitwiseANDExpression
:
BitwiseANDExpression
&
EqualityExpression
BitwiseXORExpression
:
BitwiseXORExpression
^
BitwiseANDExpression
BitwiseORExpression
:
BitwiseORExpression
|
BitwiseXORExpression
LogicalANDExpression
:
LogicalANDExpression
&&
BitwiseORExpression
LogicalORExpression
:
LogicalORExpression
||
LogicalANDExpression
CoalesceExpression
:
CoalesceExpressionHead
??
BitwiseORExpression
ConditionalExpression
:
ShortCircuitExpression
?
AssignmentExpression
:
AssignmentExpression
AssignmentExpression
:
YieldExpression
ArrowFunction
AsyncArrowFunction
LeftHandSideExpression
=
AssignmentExpression
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
LeftHandSideExpression
&&=
AssignmentExpression
LeftHandSideExpression
||=
AssignmentExpression
LeftHandSideExpression
??=
AssignmentExpression
Expression :
Expression
,
AssignmentExpression
invalid を返す。
8.6.5 静的セマンティクス: PropName
構文指向操作
PropName は引数を取らず、文字列または empty を返す。これは以下の生成規則ごとに定義される:
PropertyDefinition
: IdentifierReference
IdentifierReference
の StringValue
を返す。
PropertyDefinition
:
...
AssignmentExpression
empty を返す。
PropertyDefinition
:
PropertyName
:
AssignmentExpression
PropertyName
の PropName
を返す。
LiteralPropertyName
: IdentifierName
AttributeKey : IdentifierName
IdentifierName
の StringValue
を返す。
LiteralPropertyName
: StringLiteral
AttributeKey : StringLiteral
StringLiteral
の SV
を返す。
LiteralPropertyName
: NumericLiteral
nbr を
NumericLiteral
の NumericValue
とする。
! ToString (nbr )
を返す。
ComputedPropertyName
:
[
AssignmentExpression
]
empty を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
ClassElementName
の PropName
を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
ClassElementName
の PropName
を返す。
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
ClassElementName
の PropName
を返す。
ClassElement : ClassStaticBlock
empty を返す。
ClassElement : ;
empty を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
ClassElementName
の PropName
を返す。
FieldDefinition :
ClassElementName
Initializer opt
ClassElementName
の PropName
を返す。
ClassElementName :
PrivateIdentifier
empty を返す。
9 実行可能コードと実行コンテキスト
9.1 環境レコード
Environment Record
は、ECMAScriptコードの字句的なネスト構造に基づいて、Identifier
を特定の変数や関数に関連付けるために使用される仕様タイプです。通常、Environment Record は ECMAScript コードの FunctionDeclaration 、BlockStatement 、または Catch 節のような特定の構文構造に関連付けられています。そのようなコードが評価されるたびに、新しい
Environment Record が作成され、そのコードによって生成された識別子バインディングを記録します。
すべての Environment Record には [[OuterEnv]] フィールドがあり、これは null
か、外側の Environment Record への参照です。これは Environment Record の値の論理的なネストをモデル化するために使用されます。内側の Environment
Record の外側参照は、論理的に内側の Environment Record を取り囲む Environment Record への参照です。外側の Environment Record
もまた、自身の外側 Environment Record を持つことがあります。Environment Record は複数の内側 Environment Record
の外側環境として機能することもあります。例えば、FunctionDeclaration が2つの入れ子になった FunctionDeclaration
を含んでいる場合、各入れ子関数の Environment Record の外側 Environment Record は、囲んでいる関数の現在の評価の Environment Record
となります。
Environment Record は純粋に仕様上の仕組みであり、ECMAScript 実装の特定のアーティファクトに対応している必要はありません。ECMAScript
プログラムがこれらの値に直接アクセスしたり操作することはできません。
9.1.1 環境レコード型の階層
Environment Records は、Environment Record
が抽象クラスとして存在し、3つの具体的なサブクラスを持つ単純なオブジェクト指向の階層として考えることができます:宣言的環境レコード 、オブジェクト環境レコード 、グローバル環境レコード 。関数環境レコード とモジュール環境レコード は、宣言的環境レコード のサブクラスです。
Environment Record 抽象クラスは、表16
で定義される抽象仕様メソッドを含みます。これらの抽象メソッドは、各具体的サブクラスごとに異なる具体的アルゴリズムを持ちます。
表16: Environment Records の抽象メソッド
メソッド
目的
HasBinding(N)
Environment Record
が文字列値 N のバインディングを持つかどうか判定する。持っていれば
true 、持っていなければ false を返す。
CreateMutableBinding(N, D)
Environment Record
に新しい未初期化の可変バインディングを作成する。文字列値 N はバインド名のテキスト。ブール値 D が
true の場合、そのバインディングは後で削除可能。
CreateImmutableBinding(N, S)
Environment Record
に新しい未初期化の不変バインディングを作成する。文字列値 N はバインド名のテキスト。S が
true の場合、初期化後にセットしようとすると常に例外が投げられる(参照する操作の strict mode
設定に関わらず)。
InitializeBinding(N, V)
Environment Record
に既に存在する未初期化バインディングの値をセットする。文字列値 N はバインド名のテキスト。V
はバインディングの値で、ECMAScript
言語型 の値である。
SetMutableBinding(N, V, S)
Environment Record
に既に存在する可変バインディングの値をセットする。文字列値 N はバインド名のテキスト。V
はバインディングの値で、ECMAScript
言語型 の値である。S は Boolean
フラグ。S が true でバインディングをセットできない場合は
TypeError 例外を投げる。
GetBindingValue(N, S)
Environment Record
から既に存在するバインディングの値を返す。文字列値 N はバインド名のテキスト。S は strict mode コード からの参照や
strict mode 参照セマンティクスを必要とする他の参照を識別するために使う。S が
true かつバインディングが存在しない場合は ReferenceError
例外を投げる。バインディングが存在するが未初期化の場合は S の値に関わらず
ReferenceError を投げる。
DeleteBinding(N)
Environment
Record からバインディングを削除する。文字列値 N
はバインド名のテキスト。N のバインディングが存在する場合、それを削除して true
を返す。存在するが削除できない場合は false を返す。バインディングが存在しない場合は
true を返す。
HasThisBinding()
Environment Record が
this バインディングを確立するかどうか判定する。確立する場合は
true 、しない場合は false を返す。
HasSuperBinding()
Environment Record が
super メソッドバインディングを確立するかどうか判定する。確立する場合は
true 、しない場合は false
を返す。true を返す場合、その Environment Record は
関数環境レコード
であることを意味するが、その逆は成り立たない。
WithBaseObject()
この Environment Record が
with 文に関連付けられている場合は、その with オブジェクトを返す。それ以外の場合は
undefined を返す。
9.1.1.1 宣言的環境レコード
各宣言的環境レコード は、変数、定数、let、class、module、import、関数宣言を含むECMAScriptプログラムスコープに関連付けられています。宣言的環境レコードは、そのスコープ内に含まれる宣言によって定義された識別子の集合をバインドします。
9.1.1.1.1 HasBinding ( N )
宣言的環境レコード
envRec の HasBinding 具体メソッドは、引数 N (文字列)を取り、ブール値を含む正常完了
を返す。このメソッドは、引数の識別子がこのレコードによってバインドされている識別子の一つかどうかを判定する。呼び出されたとき次の手順を実行する:
もし envRec が N のバインディングを持っていれば、true を返す。
false を返す。
9.1.1.1.2 CreateMutableBinding ( N , D
)
宣言的環境レコード
envRec の CreateMutableBinding 具体メソッドは、引数 N (文字列)と
D (ブール値)を取り、unused
を含む正常完了 を返す。これは N という名前の新しい未初期化の可変バインディングを作成する。この
環境レコード に N
のバインディングが既に存在してはいけない。D が true
の場合、新しいバインディングは削除可能としてマークされる。呼び出されたとき次の手順を実行する:
アサート :
envRec は既に N のバインディングを持っていない。
envRec に N の可変バインディングを作成し、未初期化であることを記録する。D が
true なら、作成したバインディングが後続の DeleteBinding 呼び出しにより削除可能であることを記録する。
unused を返す。
9.1.1.1.3 CreateImmutableBinding ( N ,
S )
宣言的環境レコード
envRec の CreateImmutableBinding 具体メソッドは、引数 N (文字列)と
S (ブール値)を取り、unused
を含む正常完了 を返す。これは N という名前の新しい未初期化の不変バインディングを作成する。この
環境レコード に N
のバインディングが既に存在してはいけない。S が true の場合、新しいバインディングは strict
バインディングとしてマークされる。呼び出されたとき次の手順を実行する:
アサート :
envRec は既に N のバインディングを持っていない。
envRec に N の不変バインディングを作成し、未初期化であることを記録する。S が
true なら、作成したバインディングが strict バインディングであることを記録する。
unused を返す。
9.1.1.1.4 InitializeBinding ( N , V )
宣言的環境レコード
envRec の InitializeBinding 具体メソッドは、引数 N (文字列)と
V (ECMAScript
言語値 )を取り、unused を含む正常完了
を返す。これは、N という名前の識別子の現在のバインディングの値を V に設定するために使われる。N
の未初期化バインディングが既に存在していなければならない。呼び出されたとき次の手順を実行する:
アサート :
envRec は N の未初期化バインディングを持っていること。
envRec の N のバインディング値を V に設定する。
記録 :envRec の N
のバインディングが初期化済みであることを記録する。
unused を返す。
9.1.1.1.5 SetMutableBinding ( N , V ,
S )
宣言的環境レコード
envRec の SetMutableBinding 具体メソッドは、引数
N (文字列)、V (ECMAScript
言語値 )、S (ブール値)を取り、unused を含む正常完了
または throw completion
を返す。これは N という名前の識別子の現在のバインディング値を V に変更しようとする。通常 N
のバインディングは既に存在するが、まれに存在しない場合もある。不変バインディングの場合、S が true なら
TypeError を投げる。呼び出されたとき次の手順を実行する:
もし envRec が N のバインディングを持たない場合、
もし S が true
なら、ReferenceError 例外を投げる。
! envRec .CreateMutableBinding(N ,
true ) を実行する。
! envRec .InitializeBinding(N , V )
を実行する。
unused を返す。
もし envRec の N のバインディングが strict バインディングなら、S を
true に設定する。
もし envRec の N のバインディングが未初期化なら、
ReferenceError 例外を投げる。
それ以外で、envRec の N のバインディングが可変バインディングなら、
その値を V に変更する。
それ以外、
アサート : これは不変バインディングの値を変更しようとしている。
もし S が true
なら、TypeError 例外を投げる。
unused を返す。
注
ステップ1 でバインディングが存在しない場合の
ECMAScript コード例:
function f ( ) { eval ("var x; x = (delete x, 0);" ); }
9.1.1.1.6 GetBindingValue ( N , S )
宣言的環境レコード
envRec の GetBindingValue 具体メソッドは、引数
N (文字列)、S (ブール値)を取り、ECMAScript
言語値を含む正常完了 または throw completion
を返す。これは N という名前のバインディング値を返す。バインディングは存在するが未初期化の場合、S の値に関わらず
ReferenceError を投げる。呼び出されたとき次の手順を実行する:
アサート :
envRec は N のバインディングを持っている。
もし envRec の N のバインディングが未初期化なら
ReferenceError 例外を投げる。
envRec の N に現在バインドされている値を返す。
9.1.1.1.7 DeleteBinding ( N )
宣言的環境レコード
envRec の DeleteBinding 具体メソッドは、引数 N (文字列)を取り、ブール値を含む正常完了
を返す。明示的に削除可能と指定されたバインディングだけ削除できる。呼び出されたとき次の手順を実行する:
アサート :
envRec は N のバインディングを持っている。
もし envRec の N のバインディングが削除できない場合、false
を返す。
envRec から N のバインディングを削除する。
true を返す。
9.1.1.1.8 HasThisBinding ( )
宣言的環境レコード
envRec の HasThisBinding 具体メソッドは引数を取らず、false
を返す。呼び出されたとき次の手順を実行する:
false を返す。
注
通常の 宣言的環境レコード (すなわち
関数環境レコード でも
モジュール環境レコード
でもないもの)は this バインディングを提供しません。
9.1.1.1.9 HasSuperBinding ( )
宣言的環境レコード
envRec の HasSuperBinding 具体メソッドは引数を取らず、false
を返す。呼び出されたとき次の手順を実行する:
false を返す。
注
通常の 宣言的環境レコード (すなわち
関数環境レコード でも
モジュール環境レコード
でもないもの)は super バインディングを提供しません。
9.1.1.1.10 WithBaseObject ( )
宣言的環境レコード
envRec の WithBaseObject 具体メソッドは引数を取らず、undefined
を返す。呼び出されたとき次の手順を実行する:
undefined を返す。
9.1.1.2 オブジェクト環境レコード
各オブジェクト環境レコード は、自身のバインディングオブジェクト と呼ばれるオブジェクトに関連付けられています。オブジェクト環境レコードは、バインディングオブジェクトのプロパティ名と直接対応する文字列識別子名の集合をバインドします。プロパティキー がIdentifierName 形式の文字列でない場合は、バインドされる識別子集合に含まれません。自身のプロパティも継承プロパティも、[[Enumerable]] 属性の設定に関係なく、その集合に含まれます。オブジェクトにプロパティが動的に追加・削除できるため、オブジェクト環境レコードがバインドする識別子の集合は、プロパティの追加・削除操作の副作用として変更される可能性があります。このような副作用で作成されたバインディングは、対応するプロパティのWritable属性がfalse であっても可変バインディングとみなされます。オブジェクト環境レコードには不変バインディングは存在しません。
with文(14.11 )のために作成されるオブジェクト環境レコードは、バインディングオブジェクトを関数呼び出し時に暗黙のthis 値として提供できます。この機能はBoolean型の[[IsWithEnvironment]] フィールドで制御されます。
オブジェクト環境レコードは、表17 に示す追加の状態フィールドを持ちます。
表17: オブジェクト環境レコード の追加フィールド
フィールド名
値
意味
[[BindingObject]]
オブジェクト
この環境レコード のバインディングオブジェクト。
[[IsWithEnvironment]]
ブール値
この環境レコード がwith文のために作成されたかどうかを示す。
9.1.1.2.1 HasBinding ( N )
オブジェクト環境レコード
envRec の HasBinding 具体メソッドは、引数 N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。関連付けられたバインディングオブジェクトがN という名前のプロパティを持つかどうかを判定する。呼び出されたとき次の手順を実行する:
bindingObject をenvRec .[[BindingObject]] とする。
foundBinding を ? HasProperty (bindingObject ,
N )とする。
foundBinding がfalse なら、false を返す。
envRec .[[IsWithEnvironment]] がfalse なら、true を返す。
unscopables を ? Get (bindingObject ,
%Symbol.unscopables% )とする。
unscopables がオブジェクト の場合、
blocked をToBoolean (? Get (unscopables ,
N ))とする。
blocked がtrue なら、false を返す。
true を返す。
9.1.1.2.2 CreateMutableBinding ( N , D
)
オブジェクト環境レコード
envRec の CreateMutableBinding 具体メソッドは、引数
N (文字列)、D (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。環境レコード に関連付けられたバインディングオブジェクトにN という名前のプロパティを作成し、その値をundefined に初期化する。D がtrue なら、新しいプロパティの[[Configurable]] 属性はtrue 、そうでなければfalse に設定される。呼び出されたとき次の手順を実行する:
bindingObject をenvRec .[[BindingObject]] とする。
? DefinePropertyOrThrow (bindingObject ,
N , PropertyDescriptor { [[Value]] :
undefined , [[Writable]] :
true , [[Enumerable]] :
true , [[Configurable]] :
D })を実行する。
unused を返す。
注
通常envRec はN のバインディングを持っていませんが、持っている場合は、DefinePropertyOrThrow のセマンティクスにより既存のバインディングが置き換えられたりシャドウされたり、abrupt
completion が返されることがあります。
9.1.1.2.3 CreateImmutableBinding ( N ,
S )
オブジェクト環境レコード の
CreateImmutableBinding 具体メソッドは本仕様内で使用されません。
9.1.1.2.4 InitializeBinding ( N , V )
オブジェクト環境レコード
envRec の InitializeBinding 具体メソッドは、引数
N (文字列)、V (ECMAScript
言語値 )を取り、unused
を含む正常完了 またはthrow
completion を返す。これは、N という名前の識別子の現在のバインディング値をV に設定するために使われる。呼び出されたとき次の手順を実行する:
? envRec .SetMutableBinding (N ,
V , false )を実行する。
unused を返す。
注
本仕様では、オブジェクト環境レコード に対する
CreateMutableBinding のすべての使用は、同じ名前で直後に InitializeBinding
を呼び出します。そのため、この仕様ではオブジェクト環境レコード におけるバインディングの初期化状態を明示的に追跡しません。
9.1.1.2.5 SetMutableBinding ( N , V ,
S )
オブジェクト環境レコード
envRec の SetMutableBinding 具体メソッドは、引数
N (文字列)、V (ECMAScript
言語値 )、S (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。環境レコード に関連付けられたバインディングオブジェクトのN という名前のプロパティの値をV にセットしようとする。プロパティN は通常既に存在するが、存在しない場合や現在書き込み不可の場合、エラー処理はS で決まる。呼び出されたとき次の手順を実行する:
bindingObject をenvRec .[[BindingObject]] とする。
stillExists を ? HasProperty (bindingObject ,
N )とする。
stillExists がfalse かつS がtrue なら、ReferenceError 例外を投げる。
? Set (bindingObject ,
N , V , S )を実行する。
unused を返す。
9.1.1.2.6 GetBindingValue ( N , S )
オブジェクト環境レコード
envRec の GetBindingValue 具体メソッドは、引数
N (文字列)、S (ブール値)を取り、ECMAScript
言語値を含む正常完了 またはthrow
completion を返す。関連付けられたバインディングオブジェクトのN という名前のプロパティの値を返す。このプロパティは通常既に存在するが、存在しない場合の挙動はS による。呼び出されたとき次の手順を実行する:
bindingObject をenvRec .[[BindingObject]] とする。
value を ? HasProperty (bindingObject ,
N )とする。
value がfalse の場合、
S がfalse ならundefined を返し、そうでなければReferenceError 例外を投げる。
? Get (bindingObject ,
N )を返す。
9.1.1.2.7 DeleteBinding ( N )
オブジェクト環境レコード
envRec の DeleteBinding 具体メソッドは、引数 N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。環境オブジェクトの[[Configurable]] 属性がtrue であるプロパティに対応するバインディングだけを削除できる。呼び出されたとき次の手順を実行する:
bindingObject をenvRec .[[BindingObject]] とする。
? bindingObject .[[Delete]] (N )を返す。
9.1.1.2.8 HasThisBinding ( )
オブジェクト環境レコード
envRec の HasThisBinding
具体メソッドは引数を取らず、false を返す。呼び出されたとき次の手順を実行する:
false を返す。
注
オブジェクト環境レコード はthisバインディングを提供しません。
9.1.1.2.9 HasSuperBinding ( )
オブジェクト環境レコード
envRec の HasSuperBinding
具体メソッドは引数を取らず、false を返す。呼び出されたとき次の手順を実行する:
false を返す。
注
オブジェクト環境レコード はsuperバインディングを提供しません。
9.1.1.2.10 WithBaseObject ( )
オブジェクト環境レコード
envRec の WithBaseObject
具体メソッドは引数を取らず、オブジェクトまたはundefined を返す。呼び出されたとき次の手順を実行する:
envRec .[[IsWithEnvironment]] がtrue なら、envRec .[[BindingObject]] を返す。
それ以外の場合、undefined を返す。
9.1.1.3 関数環境レコード
関数環境レコード は、関数のトップレベルスコープを表すために使われる宣言的環境レコード であり、関数がArrowFunction でない場合はthisバインディングを提供します。関数がArrowFunction でなく、かつsuperを参照する場合、その関数環境レコードは関数内からsuperメソッド呼び出しを行うための状態も保持します。
関数環境レコードは表18 に示す追加の状態フィールドを持ちます。
表18: 関数環境レコード の追加フィールド
フィールド名
値
意味
[[ThisValue]]
ECMAScript
言語値
この関数呼び出しで使われるthis 値。
[[ThisBindingStatus]]
lexical 、initialized 、またはuninitialized
値がlexical の場合は、これはArrowFunction であり、ローカルのthis 値を持ちません。
[[FunctionObject]]
ECMAScript 関数オブジェクト
この環境レコード が作成された原因となった関数オブジェクト 。
[[NewTarget]]
コンストラクタ またはundefined
この環境レコード が[[Construct]] 内部メソッドで作成された場合、[[NewTarget]] は[[Construct]] のnewTarget パラメータの値。それ以外の場合はundefined 。
関数環境レコードは、宣言的環境レコード の表16 にあるすべてのメソッドをサポートし、HasThisBinding及びHasSuperBinding以外は同じ仕様を共有します。加えて、関数環境レコードは表19 に挙げるメソッドもサポートします。
表19: 関数環境レコード の追加メソッド
メソッド
目的
GetThisBinding()
この環境レコード のthisバインディングの値を返す。thisバインディングが初期化されていない場合はReferenceError を投げる。
9.1.1.3.1 BindThisValue ( envRec , V )
抽象操作 BindThisValue は、引数 envRec (関数環境レコード )、
V (ECMAScript 言語値 )を取り、
unused を含む正常完了
またはthrow
completion を返す。これはenvRec .[[ThisValue]] を設定し、初期化済みであることを記録する。呼び出されたとき次の手順を実行する:
アサート :
envRec .[[ThisBindingStatus]] はlexical でないこと。
envRec .[[ThisBindingStatus]] がinitialized なら、ReferenceError 例外を投げる。
envRec .[[ThisValue]] にV を設定する。
envRec .[[ThisBindingStatus]] にinitialized を設定する。
unused を返す。
9.1.1.3.2 HasThisBinding ( )
関数環境レコード
envRec の HasThisBinding 具体メソッドは引数を取らず、ブール値を返す。呼び出されたとき次の手順を実行する:
envRec .[[ThisBindingStatus]] がlexical ならfalse を返し、それ以外ならtrue を返す。
9.1.1.3.3 HasSuperBinding ( )
関数環境レコード
envRec の HasSuperBinding 具体メソッドは引数を取らず、ブール値を返す。呼び出されたとき次の手順を実行する:
envRec .[[ThisBindingStatus]] がlexical ならfalse を返す。
envRec .[[FunctionObject]] .[[HomeObject]] がundefined ならfalse を返し、それ以外ならtrue を返す。
9.1.1.3.4 GetThisBinding ( )
関数環境レコード
envRec の GetThisBinding 具体メソッドは引数を取らず、ECMAScript
言語値を含む正常完了 またはthrow
completion を返す。呼び出されたとき次の手順を実行する:
アサート :
envRec .[[ThisBindingStatus]] はlexical でないこと。
envRec .[[ThisBindingStatus]] がuninitialized なら、ReferenceError 例外を投げる。
envRec .[[ThisValue]] を返す。
9.1.1.3.5 GetSuperBase ( envRec )
抽象操作 GetSuperBase は、引数 envRec (関数環境レコード )を取り、オブジェクト、null 、またはundefined を返す。これはenvRec にバインドされたsuperプロパティアクセスの基底となるオブジェクトを返す。値がundefined の場合、そのようなアクセスは実行時エラーとなる。呼び出されたとき次の手順を実行する:
home をenvRec .[[FunctionObject]] .[[HomeObject]] とする。
home がundefined ならundefined を返す。
アサート :
home は通常のオブジェクト であること。
! home .[[GetPrototypeOf]] ()を返す。
9.1.1.4 グローバル環境レコード
グローバル環境レコード は、共通のrealm で処理されるすべてのECMAScript
Script 要素が共有する最も外側のスコープを表現するために使われます。グローバル環境レコードは、組み込みグローバル(19 )、グローバルオブジェクト のプロパティ、そしてScript 内で発生するすべてのトップレベル宣言(8.2.9 、8.2.11 )のバインディングを提供します。
グローバル環境レコードは論理的には単一のレコードですが、オブジェクト環境レコード と宣言的環境レコード をカプセル化した複合体として仕様化されています。オブジェクト環境レコード は、対応するRealm
Record のグローバルオブジェクト を基底オブジェクトとします。このグローバルオブジェクト は、グローバル環境レコードのGetThisBinding具体メソッドが返す値です。グローバル環境レコードのオブジェクト環境レコード コンポーネントは、すべての組み込みグローバル(19 )と、グローバルコード内のFunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、AsyncGeneratorDeclaration 、VariableStatement で導入されたすべてのバインディングを含みます。それ以外のグローバルコードにおけるECMAScript宣言のバインディングは、グローバル環境レコードの宣言的環境レコード コンポーネントに含まれます。
グローバルオブジェクト 上に直接プロパティが作成される場合もあります。そのため、グローバル環境レコードのオブジェクト環境レコード コンポーネントには、FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、AsyncGeneratorDeclaration 、VariableDeclaration 宣言によって明示的に作成されたバインディングと、グローバルオブジェクト のプロパティとして暗黙的に作成されたバインディングの両方が含まれることがあります。どのバインディングが宣言によって明示的に作成されたかを識別するため、グローバル環境レコードはCreateGlobalVarBinding およびCreateGlobalFunctionBinding の抽象操作 でバインドされた名前のリストを保持します。
グローバル環境レコードは、表20 に示す追加フィールドと、表21 に示す追加メソッドを持ちます。
表20: グローバル環境レコード の追加フィールド
表21: グローバル環境レコード の追加メソッド
メソッド
目的
GetThisBinding()
この環境レコード のthisバインディングの値を返す。
9.1.1.4.1 HasBinding ( N )
グローバル環境レコード
envRec の HasBinding 具体メソッドは、引数 N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。このメソッドは、引数の識別子がこのレコードによってバインドされている識別子の一つかどうかを判定する。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、true を返す。
ObjRec をenvRec .[[ObjectRecord]] とする。
? ObjRec .HasBinding (N )を返す。
9.1.1.4.2 CreateMutableBinding ( N , D
)
グローバル環境レコード
envRec の CreateMutableBinding 具体メソッドは、引数 N (文字列)と
D (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。これは N
という名前の新しい未初期化の可変バインディングを作成する。バインディングは関連するDeclarativeRecordに作成される。DeclarativeRecordに
N のバインディングが既に存在してはいけない。D が true
の場合、新しいバインディングは削除可能としてマークされる。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、TypeError 例外を投げる。
! DclRec .CreateMutableBinding(N , D )を返す。
9.1.1.4.3 CreateImmutableBinding ( N ,
S )
グローバル環境レコード
envRec の CreateImmutableBinding 具体メソッドは、引数 N (文字列)と
S (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。これは N
という名前の新しい未初期化の不変バインディングを作成する。この環境レコード にN のバインディングが既に存在してはいけない。S がtrue のとき新しいバインディングはstrictバインディングとしてマークされる。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、TypeError 例外を投げる。
! DclRec .CreateImmutableBinding(N , S )を返す。
9.1.1.4.4 InitializeBinding ( N , V )
グローバル環境レコード
envRec の InitializeBinding 具体メソッドは、引数
N (文字列)、V (ECMAScript
言語値 )を取り、unused
を含む正常完了 またはthrow
completion を返す。これは、N という名前の識別子の現在のバインディング値をV に設定するために使われる。N の未初期化バインディングが既に存在していなければならない。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、
! DclRec .InitializeBinding(N ,
V )を返す。
アサート :バインディングが存在する場合、それはオブジェクト環境レコード に存在しなければならない。
ObjRec をenvRec .[[ObjectRecord]] とする。
? ObjRec .InitializeBinding (N ,
V )を返す。
9.1.1.4.5 SetMutableBinding ( N , V ,
S )
グローバル環境レコード
envRec の SetMutableBinding 具体メソッドは、引数
N (文字列)、V (ECMAScript
言語値 )、S (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。これは N
という名前の現在のバインディング値をV に変更しようとする。不変バインディングでS がtrue ならTypeError が投げられる。プロパティN は通常既に存在するが、存在しない場合や現在書き込み不可の場合、エラー処理はS による。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、
? DclRec .SetMutableBinding(N , V ,
S )を返す。
ObjRec をenvRec .[[ObjectRecord]] とする。
? ObjRec .SetMutableBinding (N ,
V , S )を返す。
9.1.1.4.6 GetBindingValue ( N , S )
グローバル環境レコード
envRec の GetBindingValue
具体メソッドは、引数N (文字列)、S (ブール値)を取り、ECMAScript
言語値を含む正常完了 またはthrow
completion を返す。これは、N という名前のバインドされた識別子の値を返す。バインディングが未初期化の場合はReferenceError を投げる。N という名前のプロパティは通常存在するが、存在しない場合や現在書き込み不可の場合、エラー処理はS によって決まる。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、
? DclRec .GetBindingValue(N , S )を返す。
ObjRec をenvRec .[[ObjectRecord]] とする。
? ObjRec .GetBindingValue (N ,
S )を返す。
9.1.1.4.7 DeleteBinding ( N )
グローバル環境レコード
envRec の DeleteBinding 具体メソッドは、引数N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。明示的に削除可能と指定されたバインディングだけ削除できる。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )がtrue なら、
! DclRec .DeleteBinding(N )を返す。
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
existingProp を? HasOwnProperty (globalObject ,
N )とする。
existingProp がtrue なら、
? ObjRec .DeleteBinding (N )を返す。
true を返す。
9.1.1.4.8 HasThisBinding ( )
グローバル環境レコード
envRec の HasThisBinding
具体メソッドは引数を取らず、true を返す。呼び出されたとき次の手順を実行する:
true を返す。
注
グローバル環境レコード は常にthisバインディングを提供します。
9.1.1.4.9 HasSuperBinding ( )
グローバル環境レコード
envRec の HasSuperBinding
具体メソッドは引数を取らず、false を返す。呼び出されたとき次の手順を実行する:
false を返す。
注
グローバル環境レコード はsuperバインディングを提供しません。
9.1.1.4.10 WithBaseObject ( )
グローバル環境レコード
envRec の WithBaseObject
具体メソッドは引数を取らず、undefined を返す。呼び出されたとき次の手順を実行する:
undefined を返す。
9.1.1.4.11 GetThisBinding ( )
グローバル環境レコード
envRec の GetThisBinding 具体メソッドは引数を取らず、オブジェクトを含む正常完了 を返す。呼び出されたとき次の手順を実行する:
envRec .[[GlobalThisValue]] を返す。
9.1.1.4.12 HasLexicalDeclaration ( envRec ,
N )
抽象操作 HasLexicalDeclaration は、引数envRec (グローバル環境レコード )、N (文字列)を取り、ブール値を返す。これは、引数の識別子がLexicalDeclaration やClassDeclaration などレキシカル宣言で作成されたバインディングをenvRec に持つかどうかを判定する。呼び出されたとき次の手順を実行する:
DclRec をenvRec .[[DeclarativeRecord]] とする。
! DclRec .HasBinding(N )を返す。
9.1.1.4.13 HasRestrictedGlobalProperty ( envRec ,
N )
抽象操作 HasRestrictedGlobalProperty は、引数envRec (グローバル環境レコード )、N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。これは、引数の識別子が、グローバルレキシカルバインディングでシャドウされてはならないグローバルオブジェクト のプロパティ名かどうかを判定する。呼び出されたとき次の手順を実行する:
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
existingProp を? globalObject .[[GetOwnProperty]] (N )とする。
existingProp がundefined なら、false を返す。
existingProp .[[Configurable]] がtrue なら、false を返す。
true を返す。
注
グローバルオブジェクト 上には、varやfunction宣言を使わずに直接作成されたプロパティが存在する場合がある。グローバルレキシカルバインディングは、グローバルオブジェクト のnon-configurableなプロパティと同じ名前では作成できない。グローバルプロパティ"undefined" はこのようなプロパティの一例である。
9.1.1.4.14 CanDeclareGlobalVar ( envRec ,
N )
抽象操作 CanDeclareGlobalVar は、引数 envRec (グローバル環境レコード )、N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。これは、同じ引数N でCreateGlobalVarBinding を呼び出した場合に成功するかどうかを判定する。冗長なvar宣言や、既存のグローバルオブジェクト プロパティへのvar宣言は許可される。呼び出されたとき次の手順を実行する:
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
hasProperty を? HasOwnProperty (globalObject ,
N )とする。
hasProperty がtrue なら、true を返す。
? IsExtensible (globalObject )を返す。
9.1.1.4.15 CanDeclareGlobalFunction ( envRec ,
N )
抽象操作 CanDeclareGlobalFunction は、引数 envRec (グローバル環境レコード )、N (文字列)を取り、ブール値を含む正常完了 またはthrow
completion を返す。これは、同じ引数N でCreateGlobalFunctionBinding を呼び出した場合に成功するかどうかを判定する。呼び出されたとき次の手順を実行する:
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
existingProp を? globalObject .[[GetOwnProperty]] (N )とする。
existingProp がundefined なら、? IsExtensible (globalObject )を返す。
existingProp .[[Configurable]] がtrue なら、true を返す。
IsDataDescriptor (existingProp )がtrue かつexistingProp の属性値が{
[[Writable]] : true , [[Enumerable]] : true
}であれば、true を返す。
false を返す。
9.1.1.4.16 CreateGlobalVarBinding ( envRec ,
N , D )
抽象操作 CreateGlobalVarBinding は、引数 envRec (グローバル環境レコード )、N (文字列)、D (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。これは、関連するオブジェクト環境レコード に可変バインディングを作成し初期化する。バインディングがすでに存在する場合、それは再利用され、初期化済みと見なされる。呼び出されたとき次の手順を実行する:
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
hasProperty を? HasOwnProperty (globalObject ,
N )とする。
extensible を? IsExtensible (globalObject )とする。
hasProperty がfalse かつextensible がtrue なら、
? ObjRec .CreateMutableBinding (N ,
D )を実行する。
? ObjRec .InitializeBinding (N ,
undefined )を実行する。
unused を返す。
9.1.1.4.17 CreateGlobalFunctionBinding ( envRec ,
N , V , D )
抽象操作 CreateGlobalFunctionBinding は、引数 envRec (グローバル環境レコード )、N (文字列)、V (ECMAScript
言語値 )、D (ブール値)を取り、unused
を含む正常完了 またはthrow
completion を返す。これは関連するオブジェクト環境レコード に可変バインディングを作成し初期化する。バインディングがすでに存在する場合は置き換えられる。呼び出されたとき次の手順を実行する:
ObjRec をenvRec .[[ObjectRecord]] とする。
globalObject をObjRec .[[BindingObject]] とする。
existingProp を? globalObject .[[GetOwnProperty]] (N )とする。
existingProp がundefined またはexistingProp .[[Configurable]] がtrue なら、
desc をPropertyDescriptor { [[Value]] :
V , [[Writable]] :
true , [[Enumerable]] :
true , [[Configurable]] :
D }とする。
それ以外の場合、
desc をPropertyDescriptor { [[Value]] :
V }とする。
? DefinePropertyOrThrow (globalObject ,
N , desc )を実行する。
? Set (globalObject ,
N , V , false )を実行する。
unused を返す。
注
グローバル関数宣言は常にグローバルオブジェクト の独自プロパティとして表現される。可能な場合は、既存の独自プロパティは標準的な属性値セットに再設定される。ステップ7 はInitializeBinding具体メソッドを呼ぶのと同等であり、globalObject がProxyの場合は同じProxyトラップの呼び出しシーケンスを生成する。
9.1.1.5 モジュール環境レコード
モジュール環境レコード は、宣言的環境レコード であり、ECMAScript
Module の外側スコープを表現するために使用されます。通常の可変バインディングと不変バインディングに加えて、モジュール環境レコードは不変のインポートバインディングも提供します。インポートバインディングは、他の環境レコード に存在するターゲットバインディングへの間接的なアクセスを提供するバインディングです。
モジュール環境レコードは、宣言的環境レコード の表16 に記載されているすべてのメソッドをサポートし、それらのメソッドの仕様は
GetBindingValue, DeleteBinding, HasThisBinding, GetThisBinding
を除き同一です。さらに、モジュール環境レコードは表22 に挙げるメソッドもサポートします。
表22: モジュール環境レコード の追加メソッド
メソッド
目的
GetThisBinding()
この環境レコード のthisバインディングの値を返す。
9.1.1.5.1 GetBindingValue ( N , S )
モジュール環境レコード
envRec の GetBindingValue
具体メソッドは、引数N (文字列)、S (ブール値)を取り、ECMAScript
言語値を含む正常完了 またはthrow
completion を返す。これは、N という名前のバインドされた識別子の値を返す。ただし、バインディングが間接バインディングである場合はターゲットバインディングの値を返す。バインディングが未初期化の場合はReferenceError を投げる。呼び出されたとき次の手順を実行する:
アサート :S はtrue である。
アサート :envRec はN のバインディングを持っている。
もしN のバインディングが間接バインディングなら、
このN のバインディングが作成されたときに提供された間接値M およびN2 を取得する。
targetEnv をM .[[Environment]] とする。
targetEnv がempty なら、ReferenceError 例外を投げる。
? targetEnv .GetBindingValue (N2 ,
true )を返す。
envRec のN のバインディングが未初期化なら、ReferenceError 例外を投げる。
envRec のN に現在バインドされている値を返す。
注
S は常にtrue になる。なぜなら、Module は常にstrict mode コード だからである。
9.1.1.5.2 DeleteBinding ( N )
モジュール環境レコード の
DeleteBinding 具体メソッドはこの仕様内では使用されません。
注
モジュール環境レコード は厳格コード内でのみ使用され、厳格コードにおける早期エラー 規則により、delete演算子がReference
Record に適用され、その参照先がモジュール環境レコード バインディングとなることを禁止している。13.5.1.1 も参照。
9.1.1.5.3 HasThisBinding ( )
モジュール環境レコード
envRec の HasThisBinding
具体メソッドは引数を取らず、true を返す。呼び出されたとき次の手順を実行する:
true を返す。
注
モジュール環境レコード は常にthisバインディングを提供します。
9.1.1.5.4 GetThisBinding ( )
モジュール環境レコード
envRec の GetThisBinding 具体メソッドは引数を取らず、undefined
を含む正常完了 を返す。呼び出されたとき次の手順を実行する:
undefined を返す。
9.1.1.5.5 CreateImportBinding ( envRec ,
N , M , N2 )
抽象操作 CreateImportBinding は、引数 envRec (モジュール環境レコード )、N (文字列)、M (モジュールレコード )、N2 (文字列)を取り、unused を返す。これは、N という名前の新しい初期化済み不変間接バインディングを作成する。envRec にN のバインディングが既に存在してはいけない。N2 はM のモジュール環境レコード に存在するバインディング名。新しいバインディングの値へのアクセスはターゲットバインディングの値を間接的にアクセスする。呼び出されたとき次の手順を実行する:
アサート :envRec は既にN のバインディングを持っていない。
アサート :M .[[Environment]] がインスタンス化されたとき、直接N2 のバインディングを持つ。
envRec にN の不変間接バインディングを作成し、そのターゲットバインディングとしてM とN2 を参照し、初期化済みであることを記録する。
unused を返す。
9.1.2 環境レコードの操作
以下の抽象操作 は、この仕様で環境レコード を操作するために使用されます:
9.1.2.1 GetIdentifierReference ( env ,
name , strict )
抽象操作 GetIdentifierReference は、引数 env (環境レコード またはnull )、name (文字列)、strict (ブール値)を取り、Reference Record
を含む正常完了 またはthrow
completion を返します。呼び出されたとき次の手順を実行します:
env がnull なら、
Reference
Record { [[Base]] :
unresolvable , [[ReferencedName]] : name , [[Strict]] : strict , [[ThisValue]] : empty } を返す。
exists を ? env .HasBinding (name ) とする。
exists がtrue なら、
Reference
Record { [[Base]] :
env , [[ReferencedName]] :
name , [[Strict]] : strict ,
[[ThisValue]] : empty } を返す。
それ以外の場合、
outer を env .[[OuterEnv]] とする。
? GetIdentifierReference (outer ,
name , strict ) を返す。
9.1.2.2 NewDeclarativeEnvironment ( E )
抽象操作 NewDeclarativeEnvironment は、引数 E (環境レコード または
null )を取り、宣言的環境レコード
を返します。呼び出されたとき次の手順を実行します:
env をバインディングが何もない新しい 宣言的環境レコード とする。
env .[[OuterEnv]] に E を設定する。
env を返す。
9.1.2.3 NewObjectEnvironment ( O , W ,
E )
抽象操作 NewObjectEnvironment は、引数 O (オブジェクト)、W (ブール値)、E (環境レコード または
null )を取り、オブジェクト環境レコード
を返します。呼び出されたとき次の手順を実行します:
env を新しい オブジェクト環境レコード とする。
env .[[BindingObject]] に O を設定する。
env .[[IsWithEnvironment]] に W を設定する。
env .[[OuterEnv]] に E を設定する。
env を返す。
9.1.2.4 NewFunctionEnvironment ( F ,
newTarget )
抽象操作 NewFunctionEnvironment は、引数 F (ECMAScript 関数オブジェクト )、newTarget (オブジェクトまたは
undefined )を取り、関数環境レコード
を返します。呼び出されたとき次の手順を実行します:
env をバインディングが何もない新しい 関数環境レコード とする。
env .[[FunctionObject]] に F を設定する。
F .[[ThisMode]] が lexical
なら、env .[[ThisBindingStatus]] に
lexical を設定する。
それ以外の場合、env .[[ThisBindingStatus]] に
uninitialized を設定する。
env .[[NewTarget]] に newTarget を設定する。
env .[[OuterEnv]] に F .[[Environment]] を設定する。
env を返す。
9.1.2.5 NewGlobalEnvironment ( G ,
thisValue )
抽象操作 NewGlobalEnvironment は、引数 G (オブジェクト)、thisValue (オブジェクト)を取り、グローバル環境レコード
を返します。呼び出されたとき次の手順を実行します:
objRec を NewObjectEnvironment (G ,
false , null ) とする。
dclRec を NewDeclarativeEnvironment (null )
とする。
env を新しい グローバル環境レコード とする。
env .[[ObjectRecord]] に objRec を設定する。
env .[[GlobalThisValue]] に thisValue
を設定する。
env .[[DeclarativeRecord]] に dclRec
を設定する。
env .[[OuterEnv]] に null
を設定する。
env を返す。
9.1.2.6 NewModuleEnvironment ( E )
抽象操作 NewModuleEnvironment は、引数 E (環境レコード )を取り、モジュール環境レコード
を返します。呼び出されたとき次の手順を実行します:
env をバインディングが何もない新しい モジュール環境レコード とする。
env .[[OuterEnv]] に E を設定する。
env を返す。
9.2 プライベート環境レコード
プライベート環境レコード は、ECMAScriptコード内のClassDeclaration やClassExpression の字句的入れ子構造に基づいてプライベート名 を追跡するために使われる仕様メカニズムです。これは環境レコード に似ていますが、異なるものです。各プライベート環境レコード は、ClassDeclaration またはClassExpression に関連付けられています。このようなクラスが評価されるたびに、そのクラスによって宣言されたプライベート名 を記録する新しいプライベート環境レコード が作成されます。
各プライベート環境レコード は、表23 で定義されたフィールドを持ちます。
表23: プライベート環境レコード のフィールド
9.2.1 プライベート環境レコードの操作
以下の抽象操作 は、この仕様でプライベート環境レコード を操作するために使用されます:
9.2.1.1 NewPrivateEnvironment ( outerPrivateEnv )
抽象操作 NewPrivateEnvironment は、引数 outerPrivateEnv (プライベート環境レコード または
null )を取り、プライベート環境レコード を返す。呼び出されたとき次の手順を実行する:
names を新しい空の リスト とする。
プライベート環境レコード { [[OuterPrivateEnvironment]] : outerPrivateEnv ,
[[Names]] : names } を返す。
9.2.1.2 ResolvePrivateIdentifier ( privateEnv ,
identifier )
抽象操作 ResolvePrivateIdentifier は、引数 privateEnv (プライベート環境レコード )、identifier (文字列)を取り、プライベート名 を返す。呼び出されたとき次の手順を実行する:
names を privateEnv .[[Names]] とする。
names の各プライベート名 pn について、
pn .[[Description]] が
identifier であれば、
pn を返す。
outerPrivateEnv を privateEnv .[[OuterPrivateEnvironment]] とする。
アサート :outerPrivateEnv はnull ではない。
ResolvePrivateIdentifier (outerPrivateEnv ,
identifier ) を返す。
9.3 レルム
評価される前に、すべてのECMAScriptコードはレルム に関連付けられていなければなりません。概念的には、レルム は、一連の組み込みオブジェクト、ECMAScriptグローバル環境、そのグローバル環境のスコープ内でロードされたすべてのECMAScriptコード、およびその他の関連する状態やリソースから構成されます。
レルム は、この仕様ではレルムレコード として表現され、表24 で指定されるフィールドを持ちます:
表24: レルムレコード のフィールド
9.3.1 InitializeHostDefinedRealm ( )
抽象操作 InitializeHostDefinedRealm は引数を取らず、unused
を含む正常完了 またはthrow
completion を返す。呼び出されたとき次の手順を実行する:
realm を新しいレルムレコード とする。
CreateIntrinsics (realm )を実行する。
realm .[[AgentSignifier]] にAgentSignifier ()の値を設定する。
realm .[[TemplateMap]] に新しい空のリスト を設定する。
newContext を新しい実行コンテキスト とする。
newContext のFunctionをnull に設定する。
newContext のレルム をrealm に設定する。
newContext のScriptOrModuleをnull に設定する。
newContext を実行コンテキストスタック にプッシュする。newContext が実行中の実行コンテキスト となる。
ホスト がエキゾチックオブジェクト をrealm のグローバルオブジェクト として必要とする場合、
global をそのようなオブジェクトとしてホスト定義 の方法で作成する。
それ以外の場合、
global をOrdinaryObjectCreate (realm .[[Intrinsics]] .[[%Object.prototype% ]])とする。
ホスト がrealm のグローバルスコープのthisバインディングをグローバルオブジェクト 以外のオブジェクトにする必要がある場合、
thisValue をそのようなオブジェクトとしてホスト定義 の方法で作成する。
それ以外の場合、
thisValue をglobal とする。
realm .[[GlobalObject]] にglobal を設定する。
realm .[[GlobalEnv]] にNewGlobalEnvironment (global ,
thisValue )を設定する。
? SetDefaultGlobalBindings (realm )を実行する。
ホスト定義 のグローバルオブジェクト プロパティをglobal に作成する。
unused を返す。
9.3.2 CreateIntrinsics ( realmRec )
抽象操作 CreateIntrinsics は、引数 realmRec (レルムレコード )を取り、unused を返す。呼び出されたとき次の手順を実行する:
realmRec .[[Intrinsics]] に新しいレコード を設定する。
realmRec .[[Intrinsics]] のフィールドに、表6 に記載の値を設定する。フィールド名は表の第1列。値は、この仕様の
19 から 28
各オブジェクトの仕様に従って完全かつ再帰的にプロパティ値が設定された新しいオブジェクト値。すべてのオブジェクトプロパティ値は新しいオブジェクト値。組み込み関数オブジェクト は CreateBuiltinFunction (steps ,
length , name , slots , realmRec ,
prototype )
で作成される。steps はこの仕様で定義された関数、name は関数の"name" プロパティの初期値、length は"length" プロパティの初期値、slots は内部スロット名リスト、prototype は[[Prototype]] 内部スロットの指定値。組み込みとそのプロパティの作成順序は、未作成のオブジェクトへの依存が発生しないようにしなければならない。
AddRestrictedFunctionProperties (realmRec .[[Intrinsics]] .[[%Function.prototype% ]],
realmRec )を実行する。
unused を返す。
9.3.3 SetDefaultGlobalBindings ( realmRec )
抽象操作 SetDefaultGlobalBindings は、引数 realmRec (レルムレコード )を取り、unused
を含む正常完了 またはthrow
completion を返す。呼び出されたとき次の手順を実行する:
global をrealmRec .[[GlobalObject]] とする。
19 で指定されるグローバルオブジェクトの各プロパティについて、
name をプロパティ名 の文字列値とする。
desc を、そのプロパティの指定属性を含む完全なデータプロパティディスクリプタ とする。19.2 、19.3 、19.4 に列挙されるプロパティの場合、[[Value]] 属性の値はrealmRec の対応する組み込みオブジェクト。
? DefinePropertyOrThrow (global ,
name , desc )を実行する。
unused を返す。
9.4 実行コンテキスト
実行コンテキスト は、ECMAScriptの実装によるコードの実行時評価を追跡するために使用される仕様デバイスです。任意の時点で、実際にコードを実行しているエージェント ごとに最大1つの実行コンテキストしか存在しません。これは、そのエージェント の実行中の実行コンテキスト として知られます。本仕様における実行中の実行コンテキスト へのすべての参照は、周囲のエージェント の実行中の実行コンテキスト を指します。
実行コンテキストスタック は、実行コンテキストを追跡するために使用されます。実行中の実行コンテキスト は常にこのスタックの最上位要素です。現在の実行中の実行コンテキスト に関連付けられている実行可能コードから、関連付けられていない実行可能コードへ制御が移るたびに、新しい実行コンテキストが作成されます。新たに作成された実行コンテキストはスタックにプッシュされ、実行中の実行コンテキスト となります。
実行コンテキストは、それに関連付けられたコードの実行進捗を追跡するために必要な実装依存の状態を含みます。各実行コンテキストは、少なくとも表25 に記載された状態コンポーネントを持ちます。
表25: すべての実行コンテキストの状態コンポーネント
Evaluation により、実行中の実行コンテキスト によるコードの評価は、本仕様で定義された様々な時点で中断されることがあります。実行中の実行コンテキスト が中断された場合、別の実行コンテキストが実行中の実行コンテキスト となり、そのコードの評価を開始します。後の時点で、中断されていた実行コンテキストが再び実行中の実行コンテキスト となり、中断された箇所からコードの評価を再開することがあります。実行中の実行コンテキスト の状態遷移は通常、スタックの後入れ先出し(LIFO)の方法で行われます。ただし、一部のECMAScriptの機能では、実行中の実行コンテキスト の非LIFOな遷移が必要となることがあります。
Realm コンポーネントの値は、実行中の実行コンテキスト において現在のRealm Record とも呼ばれます。実行中の実行コンテキスト のFunctionコンポーネントの値はアクティブな関数オブジェクト とも呼ばれます。
ECMAScriptコード実行コンテキスト は、表26 に記載された追加の状態コンポーネントを持ちます。
表26: ECMAScriptコード実行コンテキストの追加状態コンポーネント
実行コンテキストのLexicalEnvironmentおよびVariableEnvironmentコンポーネントは常にEnvironment Record です。
ジェネレーターの評価を表す実行コンテキストは、表27 に記載された追加の状態コンポーネントを持ちます。
表27: ジェネレーター実行コンテキストの追加状態コンポーネント
コンポーネント
目的
Generator
この実行コンテキスト が評価しているGenerator。
ほとんどの場合、仕様内のアルゴリズムによって直接操作されるのは実行中の実行コンテキスト (実行コンテキストスタック の最上位)だけです。そのため、「LexicalEnvironment」や「VariableEnvironment」という用語が修飾なしで使われている場合、それは実行中の実行コンテキスト のこれらのコンポーネントを指します。
実行コンテキストは純粋に仕様上の仕組みであり、ECMAScript実装の特定の構造体に対応している必要はありません。ECMAScriptコードから直接実行コンテキストにアクセスしたり観察したりすることはできません。
9.4.1 GetActiveScriptOrModule ( )
抽象操作GetActiveScriptOrModuleは引数を取らず、Script Record 、Module
Record 、またはnull を返します。これは実行中の実行コンテキスト に基づき、現在実行中のスクリプトまたはモジュールを判定するために使用されます。呼び出し時、次の手順を実行します:
もし実行コンテキストスタック が空であれば、null を返す。
ec を、実行コンテキストスタック 上のScriptOrModuleコンポーネントがnull でない最上位の実行コンテキスト とする。
そのような実行コンテキスト が存在しない場合、null を返す。そうでなければ、ec のScriptOrModuleを返す。
9.4.2 ResolveBinding ( name [ , env ] )
抽象操作ResolveBindingは、引数name (文字列)および省略可能な引数env (Environment
Record またはundefined )を取り、normal completion
containing なReference
Record またはthrow
completion のいずれかを返します。これはname のバインディングを判定するために使用されます。env でバインディングを検索するEnvironment
Record を明示的に指定できます。呼び出し時、次の手順を実行します:
もしenv が指定されていない、またはenv がundefined の場合、
env に実行中の実行コンテキスト のLexicalEnvironmentを設定する。
保証 :env はEnvironment Record である。
strict をIsStrict (評価中の構文生成規則)とする。
戻り値は? GetIdentifierReference (env ,
name , strict )とする。
注
ResolveBindingの結果は常に、その[[ReferencedName]] フィールドがname となるReference
Record です。
9.4.3 GetThisEnvironment ( )
抽象操作GetThisEnvironmentは引数を取らず、Environment Record を返します。これは、現在キーワード thisのバインディングを提供するEnvironment
Record を見つけます。呼び出し時、次の手順を実行します:
env を実行中の実行コンテキスト のLexicalEnvironmentとする。
繰り返す。
exists をenv .HasThisBinding()とする。
もしexists がtrue なら、env を返す。
outer をenv .[[OuterEnv]] とする。
保証 :outer はnull でない。
env にouter を設定する。
注
ステップ2 のループは必ず終了します。なぜなら、環境のリストは必ずthisバインディングを持つグローバル環境で終わるからです。
9.4.4 ResolveThisBinding ( )
抽象操作ResolveThisBindingは引数を取らず、normal completion
containing なECMAScript言語値 またはthrow
completion を返します。これは、実行中の実行コンテキスト のLexicalEnvironmentを使ってキーワード thisのバインディングを決定します。呼び出し時、次の手順を実行します:
envRec をGetThisEnvironment ()とする。
戻り値は? envRec .GetThisBinding()とする。
9.4.5 GetNewTarget ( )
抽象操作GetNewTargetは引数を取らず、オブジェクトまたはundefined を返します。これは、実行中の実行コンテキスト のLexicalEnvironmentを使ってNewTarget値を決定します。呼び出し時、次の手順を実行します:
envRec をGetThisEnvironment ()とする。
保証 :envRec は[[NewTarget]] フィールドを持つ。
戻り値はenvRec .[[NewTarget]] とする。
9.4.6 GetGlobalObject ( )
抽象操作GetGlobalObjectは引数を取らず、オブジェクトを返します。これは、現在の実行中の実行コンテキスト が使用するグローバルオブジェクト を返します。呼び出し時、次の手順を実行します:
currentRealm を現在のRealm Record とする。
戻り値はcurrentRealm .[[GlobalObject]] とする。
9.5 ジョブおよびジョブをキューに入れるためのホスト操作
ジョブ とは、パラメータを持たず、他のECMAScript計算が現在進行中でないときにECMAScript計算を開始する抽象クロージャ です。
ジョブ は、ECMAScriptホスト環境 によって、特定のエージェント で実行されるようにスケジュールされます。本仕様では、ジョブをスケジュールするためのホストフック であるHostEnqueueGenericJob 、HostEnqueueFinalizationRegistryCleanupJob 、HostEnqueuePromiseJob 、およびHostEnqueueTimeoutJob を説明します。本仕様のホストフック は、ジョブのスケジューリングに課される追加の制約によって整理されています。ホスト は、さらにジョブをスケジュールする抽象操作 を定義してもかまいません。そのような操作は、ジョブ となる抽象クロージャ と、realm (Realm
Record またはnull )をパラメータとして受け取ります。Realm
Record が指定された場合、これらの操作は、そのrealm を所有するエージェント で、提供されたrealm で将来のある時点でジョブを実行するようにスケジュールします。realm にnull が指定された場合、そのジョブはECMAScriptコードを評価しません。これらの実装は、以下の要件に準拠しなければなりません。
注1
ホスト環境 は、スケジューリングに関して
ジョブ を一様に扱う必要はありません。例えば、WebブラウザやNode.jsはPromise処理の
ジョブ を他の作業よりも高い優先度で扱います。将来の機能追加では、これほど高い優先度で扱われない
ジョブ が追加される可能性があります。
ある時点で、すべての次の条件が真であれば、scriptOrModule (Script Record 、Module
Record 、またはnull )はアクティブなスクリプトまたはモジュール です:
ある時点で、すべての次の条件が真であれば、実行はECMAScriptコードを評価する準備ができている 状態です:
注2
ホスト環境 は、実行コンテキストスタック に実行コンテキスト をプッシュすることで、コード評価のための実行準備を行うことがあります。その具体的なステップは実装依存 です。
Realm の具体的な選択はホスト環境 に委ねられます。この初期の実行コンテキスト とRealm は、コールバック関数が呼び出される前にのみ使用されます。Promiseハンドラのようなジョブ に関連するコールバック関数が呼び出されると、その呼び出しは自身の実行コンテキスト とRealm をプッシュします。
特定の種類のジョブ には、追加の適合要件があります。
9.5.1 JobCallbackレコード
JobCallbackレコード は、Record 値であり、関数オブジェクト およびホスト定義 値を保存するために使われます。ホスト によってキューに入れられたジョブ を通して呼び出される関数オブジェクト は、追加のホスト定義 コンテキストを持つ場合があります。この状態を伝播するために、ジョブ の抽象クロージャ は、関数オブジェクトを直接キャプチャして呼び出すべきではありません。代わりにHostMakeJobCallback とHostCallJobCallback を使用してください。
注
WHATWG HTML仕様(https://html.spec.whatwg.org/ )は、例えばPromiseコールバックのためにインカンバント設定オブジェクトを伝播するためにホスト定義 値を利用します。
JobCallbackレコードは、表28 に示すフィールドを持ちます。
表28: JobCallback Record フィールド
フィールド名
値
意味
[[Callback]]
関数オブジェクト
ジョブ が呼び出されたときに呼び出す関数。
[[HostDefined]]
任意の値(デフォルト値はempty )
ホスト が利用するためのフィールド。
9.5.2 HostMakeJobCallback ( callback )
ホスト定義 抽象操作HostMakeJobCallbackは、引数callback (関数オブジェクト )を受け取り、JobCallbackレコード を返します。
HostMakeJobCallbackの実装は、以下の要件を満たさなければなりません:
HostMakeJobCallbackのデフォルト実装は、呼び出し時に次の手順を実行します:
JobCallbackレコード { [[Callback]] : callback , [[HostDefined]] : empty }を返す。
WebブラウザでないECMAScriptホスト は、HostMakeJobCallbackのデフォルト実装を使用しなければなりません。
注
これは、コールバックが最終的にスケジュールされ実行される責任を持つ関数に渡された時点で呼び出されます。たとえば、promise.then(thenAction)はPromise.prototype.thenの呼び出し時にthenActionに対してMakeJobCallbackを呼び出しますが、リアクションジョブ がスケジュールされる時ではありません。
9.5.3 HostCallJobCallback ( jobCallback , V ,
argumentsList )
ホスト定義 抽象操作HostCallJobCallbackは、引数jobCallback (JobCallbackレコード )、V (ECMAScript言語値 )、argumentsList (List (各要素はECMAScript言語値 ))を受け取り、normal completion
containing なECMAScript言語値 またはthrow completion を返します。
HostCallJobCallbackの実装は、以下の要件を満たさなければなりません:
Call (jobCallback .[[Callback]] , V ,
argumentsList )を実行し、その結果を返さなければなりません。
注
この要件は、ホスト が本仕様で定義された関数オブジェクト の[[Call]] の動作を変更できないことを意味します。
HostCallJobCallbackのデフォルト実装は、呼び出し時に次の手順を実行します:
保証 : IsCallable (jobCallback .[[Callback]] )はtrue である。
? Call (jobCallback .[[Callback]] , V , argumentsList )を返す。
WebブラウザでないECMAScriptホスト は、HostCallJobCallbackのデフォルト実装を使用しなければなりません。
9.5.4 HostEnqueueGenericJob ( job , realm )
ホスト定義 抽象操作HostEnqueueGenericJobは、引数job (ジョブ 抽象クロージャ )とrealm (Realm
Record )を受け取り、unused を返します。これは、realm .[[AgentSignifier]] で示されるエージェント 内のrealm realm でjob を将来のある時点で実行するようにスケジュールします。このアルゴリズムで利用される抽象クロージャ は、優先度や順序などの追加制約なしにスケジュールされることを意図しています。
HostEnqueueGenericJobの実装は、9.5 の要件に準拠しなければなりません。
9.5.5 HostEnqueuePromiseJob ( job , realm )
ホスト定義 抽象操作HostEnqueuePromiseJobは、引数job (ジョブ 抽象クロージャ )とrealm (Realm
Record またはnull )を受け取り、unused を返します。これは、job を将来のある時点で実行するようにスケジュールします。このアルゴリズムで利用される抽象クロージャ は、Promiseの処理に関連するか、Promise処理操作と同等の優先度でスケジュールされることを意図しています。
HostEnqueuePromiseJobの実装は、9.5 の要件に加えて、次の要件にも準拠しなければなりません:
注
NewPromiseResolveThenableJob が返すジョブ のrealm は、通常then 関数オブジェクト に対してGetFunctionRealm を呼び出した結果となります。NewPromiseReactionJob が返すジョブ のrealm は、通常ハンドラがundefined でなければ、そのハンドラに対してGetFunctionRealm を呼び出した結果となります。ハンドラがundefined の場合、realm はnull です。両方のジョブ について、GetFunctionRealm が異常終了した場合(例:revokeされたProxy上で呼び出された場合)、realm は現在のRealm
Record になります。realm がnull の場合、ユーザーECMAScriptコードは評価されず、新たなECMAScriptオブジェクト(例:Errorオブジェクト)は作成されません。例えばWHATWG
HTML仕様(https://html.spec.whatwg.org/ )では、realm を使ってスクリプトの実行可否やentry 概念のチェックを行います。
9.5.6 HostEnqueueTimeoutJob ( timeoutJob ,
realm , milliseconds )
ホスト定義 抽象操作HostEnqueueTimeoutJobは、引数timeoutJob (Job 抽象クロージャ )、realm (Realm
Record )、およびmilliseconds (非負の有限 数値)を取り、unused を返す。これは、realm realm 内のagent (realm .[[AgentSignifier]] で示される)において、少なくともmilliseconds ミリ秒後にtimeoutJob が実行されるようにスケジューリングする。
HostEnqueueTimeoutJobの実装は、9.5 の要件に準拠しなければならない。
9.6 エージェント
エージェント は、一連のECMAScript実行コンテキスト 、実行コンテキストスタック 、実行中の実行コンテキスト 、エージェントレコード 、および実行スレッド から構成されます。実行スレッド を除き、エージェント の構成要素はそのエージェント にのみ属します。
エージェント の実行スレッド は、他のエージェント とは独立して、そのエージェント の実行コンテキスト 上でアルゴリズムステップを実行します。ただし、実行スレッド が、複数のエージェント によって使用されることがあっても、スレッドを共有しているエージェント のいずれも、そのエージェントレコード の[[CanBlock]] フィールドがtrue でない限り許されます。
注1
例えば、一部のウェブブラウザーは、複数の無関係なタブ間で一つの実行スレッド を共有します。
エージェント の実行スレッド がアルゴリズムステップを実行している間、そのエージェント はこれらのステップの周囲のエージェント となります。これらのステップは周囲のエージェント を使って、エージェント 内に保持された仕様レベルの実行オブジェクト(実行中の実行コンテキスト 、実行コンテキストスタック 、エージェントレコード のフィールド)へアクセスします。
エージェント識別子 は、エージェント を識別するために使用されるグローバルに一意な不透明値です。
表29: エージェントレコード のフィールド
フィールド名
値
意味
[[LittleEndian]]
Boolean
GetValueFromBuffer およびSetValueInBuffer アルゴリズムでisLittleEndian パラメータが必要な場合のデフォルト値。値の選択は実装依存 であり、実装にとって最も効率的な代替案であるべきです。一度観測された値は変更できません。
[[CanBlock]]
Boolean
エージェント がブロック可能かどうかを決定します。
[[Signifier]]
エージェント識別子
自身のエージェントクラスタ 内でエージェント を一意に識別します。
[[IsLockFree1]]
Boolean
1バイト値 のアトミック操作がロックフリーならtrue 、そうでなければfalse 。
[[IsLockFree2]]
Boolean
2バイト値 のアトミック操作がロックフリーならtrue 、そうでなければfalse 。
[[IsLockFree8]]
Boolean
8バイト値 のアトミック操作がロックフリーならtrue 、そうでなければfalse 。
[[CandidateExecution]]
候補実行 のRecord
メモリーモデル を参照。
[[KeptAlive]]
List (要素はObjectまたはSymbol)
新たな空List から始まり、現在のJob が終了するまで生存させるべきオブジェクトやシンボルのリスト。
[[ModuleAsyncEvaluationCount]]
整数
初期値0。非同期もしくは非同期依存を持つモジュールの[[AsyncEvaluationOrder]] フィールドに一意な増加値を割り当てるために使用。
[[Signifier]] 、[[IsLockFree1]] 、[[IsLockFree2]] の値は、一度エージェントクラスタ 内のいずれかのエージェント によって観測された場合、変更できません。
注2
[[IsLockFree1]] および[[IsLockFree2]] の値は、必ずしもハードウェアによって決まるものではなく、実装ごと・時間ごとに異なる実装選択を反映することがあります。
[[IsLockFree4]] フィールドは存在しません。4バイトのアトミック操作は常にロックフリーです。
実際には、アトミック操作が何らかのロックを伴って実装されている場合、その操作はロックフリーではありません。ロックフリーはウェイトフリーを意味せず、ロックフリーなアトミック操作を完了するのに必要なマシンステップ数に上限はありません。
サイズn のアトミックアクセスがロックフリーであることは、サイズn の非アトミックアクセスの(見かけ上の)アトミシティについては何も意味しません。具体的には、非アトミックアクセスは複数の個別なメモリアクセスの連続として実行されることがあります。詳細はReadSharedMemory およびWriteSharedMemory を参照してください。
注3
エージェント は仕様上の仕組みであり、ECMAScript実装の特定の構造体に対応している必要はありません。
9.6.1 AgentSignifier ( )
抽象操作AgentSignifierは引数を取らず、エージェント識別子 を返します。呼び出し時、次の手順を実行します:
AR を周囲のエージェント のエージェントレコード とする。
AR .[[Signifier]] を返す。
9.6.2 AgentCanSuspend ( )
抽象操作AgentCanSuspendは引数を取らず、Booleanを返します。呼び出し時、次の手順を実行します:
AR を周囲のエージェント のエージェントレコード とする。
AR .[[CanBlock]] を返す。
注
環境によっては、特定のエージェント のサスペンドが合理的でない場合があります。例えば、ウェブブラウザー環境では、ドキュメントのメインイベント処理スレッドのサスペンドを許可せず、ワーカーのイベント処理スレッドのみサスペンドを許可するのが合理的かもしれません。
9.6.3 IncrementModuleAsyncEvaluationCount ( )
抽象操作IncrementModuleAsyncEvaluationCountは引数を取らず、整数 を返します。呼び出し時、次の手順を実行します:
AR を周囲のエージェント のエージェントレコード とする。
count をAR .[[ModuleAsyncEvaluationCount]] とする。
AR .[[ModuleAsyncEvaluationCount]] にcount +1を設定する。
count を返す。
注
この値は未処理モジュール間の相対評価順序を追跡するためだけに使用されます。未処理モジュールが存在しない場合、実装は[[ModuleAsyncEvaluationCount]] を密かに0にリセットしてもかまいません。
9.7 エージェントクラスタ
エージェントクラスタ は、共有メモリ上で操作することで通信できるエージェント の極大集合です。
注1
異なるエージェント のプログラムは、未規定の手段でメモリを共有する場合があります。少なくとも、SharedArrayBufferのバックメモリはクラスタ内のエージェント 間で共有できます。
メッセージパッシングによってのみ通信でき、メモリを共有できないエージェント も存在する場合があります。これらは決して同じエージェントクラスタには属しません。
すべてのエージェント は、正確に1つのエージェントクラスタに属します。
注2
クラスタ内のエージェント は、ある時点ですべてが生存している必要はありません。エージェント A が別のエージェント B を生成し、その後A が終了し、B がエージェント C を生成した場合、A がB とメモリを共有でき、B がC とメモリを共有できるなら、この3つのエージェント は同じクラスタに属します。
クラスタ内のすべてのエージェント は、それぞれのエージェントレコード の[[LittleEndian]] フィールドの値が同じでなければなりません。
注3
同一エージェントクラスタ内で異なるエージェント が異なる[[LittleEndian]] 値を持つ場合、複数バイトデータの共有メモリ利用が困難になります。
クラスタ内のすべてのエージェント は、それぞれのエージェントレコード の[[IsLockFree1]] フィールドの値が同じでなければなりません。[[IsLockFree2]] フィールドについても同様です。
クラスタ内のすべてのエージェント は、それぞれのエージェントレコード の[[Signifier]] フィールドの値が異なっていなければなりません。
埋め込み環境は、エージェント の知識や協力なしに、そのエージェント の進行を停止(非アクティブ化)または再開(アクティブ化)してもかまいません。その場合、クラスタ内の一部のエージェント だけがアクティブなまま、他のエージェント が無期限に非アクティブな状態にしてはなりません。
注4
この制約は、他のエージェント が非アクティブ化された結果、エージェント がデッドロックやスターブ状態になる事態を防ぐためです。たとえば、HTMLの共有ワーカーがウィンドウのドキュメントと独立して存続でき、独立したドキュメントの専用ワーカーとメモリを共有できる場合、そのドキュメントと専用ワーカーが非アクティブ化され、専用ワーカーがロックを保持していた場合(例えばドキュメントがウィンドウ履歴にプッシュされた場合)、共有ワーカーがそのロック取得を試みると、専用ワーカーが再度アクティブ化されるまでブロックされます。その間、他のウィンドウから共有ワーカーへのアクセスを試みるワーカーはスターブします。
この制約の帰結として、埋め込み環境内で同じサスペンド/ウェイク集団に属さないエージェント 同士でメモリを共有することはできなくなります。
埋め込み環境は、クラスタ内の他のエージェント の事前の知識や協力なしにエージェント を終了させてもかまいません。もしエージェント が自身またはクラスタ内の他のエージェント によるプログラム的操作でなく、クラスタ外部の要因で終了させられる場合、埋め込み環境は2つの戦略のいずれかを選ばなければなりません:クラスタ内のすべてのエージェント を終了させるか、クラスタ内のエージェント が協調できる信頼性のあるAPIを提供し、クラスタ内の少なくとも1つのメンバーが終了を検知できるようにし、終了データには終了したエージェント を特定できる十分な情報を含めること。
注5
この種の終了の例:異なるプロセスで動作するエージェント をOSやユーザーが終了させる場合、同じプロセス内で他のエージェント と共に動作しているエージェント を、エージェント単位のリソース管理に基づき暴走と判定されて終了させる場合など。
以下の仕様値およびそれらから伝播的に到達可能な値は、正確に1つのエージェントクラスタに属します。
クラスタ内のいずれかのエージェント によるECMAScriptコードの評価前に、クラスタ内のすべてのエージェントレコード の[[CandidateExecution]] フィールドは初期候補実行 に設定されます。初期候補実行 は、[[EventsRecords]] フィールドが、各エージェント についてそのエージェント識別子 を[[AgentSignifier]] フィールドに持ち、[[EventList]] および[[AgentSynchronizesWith]] フィールドが空List であるAgent Events
Record を格納したList である、空の候補実行 です。
注6
同じエージェントクラスタ内のすべてのエージェント は、エージェントレコード の[[CandidateExecution]] フィールドで同じ候補実行 を共有します。候補実行 はメモリーモデル で使用される仕様の仕組みです。
注7
エージェントクラスタは仕様上の仕組みであり、ECMAScript実装の特定の構造物に対応している必要はありません。
9.8 フォワードプログレス
エージェント がフォワードプログレスを行う とは、本仕様に従って評価ステップを実行することを指します。
エージェント は、その実行中の実行コンテキスト が外部イベントを同期的かつ無期限に待機する場合にブロック されます。この意味でブロックされるのは、エージェント のエージェントレコード の[[CanBlock]] フィールドがtrue である場合のみです。アンブロック されたエージェント は、ブロックされていないものを指します。
実装は以下を保証しなければなりません:
注
これはメモリーモデル におけるライブネス保証と合わせて、すべてのseq-cst 書き込みが最終的にすべてのエージェント から観測可能になることを保証します。
9.9 WeakRefおよびFinalizationRegistryターゲットの処理モデル
9.9.1 目標
本仕様は、いかなるオブジェクトやシンボルもガベージコレクションされることを保証しません。ライブ でないオブジェクトやシンボルは、長い期間の後に解放されることも、まったく解放されないこともあります。このため、本仕様ではガベージコレクションによって引き起こされる挙動について「may」という表現を使用します。
WeakRef およびFinalizationRegistry のセマンティクスは、特定のタイミングで発生する2つの操作に基づいています:
これらのアクション(ClearKeptObjects またはCleanupFinalizationRegistry )は、同期的なECMAScript実行を中断してはなりません。ホスト がより長い同期的なECMAScript実行を構成することがあるため、本仕様ではClearKeptObjects およびCleanupFinalizationRegistry のスケジューリングをホスト環境 に委ねます。
一部のECMAScript実装には、ECMAScriptがアイドル状態のときも含めてバックグラウンドで動作するガベージコレクタの実装が含まれています。ホスト環境 がCleanupFinalizationRegistry をスケジュールできることで、ファイナライザ処理を実行するためにECMAScriptの実行を再開し、保持値を解放して全体のメモリ使用量を削減できるようになります。
9.9.2 ライブネス
あるオブジェクトやシンボルの集合S について、仮想的なWeakRef非考慮 実行とは、S の要素を参照するWeakRefDeref 抽象操作が常にundefined を返すような実行のことです。
注1
WeakRef 非考慮性とライブネスは2つの概念を捉えます。1つは
WeakRef 自身は参照先を生存させないこと。もう1つはライブネスの循環がその値がライブであることを意味しないことです。具体的には、ある
v のライブネス判定が
WeakRef 参照先
r のライブネスに依存している場合、
r のライブネスは
v のライブネスを前提にしてはなりません(循環論法禁止)。
注2
WeakRef 非考慮性は、サイクルを考慮するために個々の値ではなく集合に対して定義されています。もし個々の値で定義した場合、サイクル内の
WeakRef 参照先は、サイクル内の他の
WeakRef 参照先を通じてのみ識別される場合にもライブと見なされてしまいます。
注3
通常、個々のオブジェクトやシンボルがライブであるとは、それを含むすべての集合がライブである場合を指します。
評価中の任意の時点で、オブジェクトやシンボルの集合S は、次のいずれかの条件を満たす場合にライブ と見なされます:
S 内のいずれかの要素が、いずれかのエージェント の[[KeptAlive]] List に含まれている。
S のいずれかの値の識別性を観測する有効な将来の仮想的なWeakRef非考慮実行が存在する。
注4
上記2番目の条件は、値が非
WeakRef 手段で識別可能な場合にライブである、という直感を捉えています。値の識別性は、厳密等価比較やMapのキーとして使われることで観測できます。
注5
フィールド、内部スロット、またはプロパティにオブジェクトやシンボルが存在することは、その値がライブであることを意味しません。たとえば、その値がプログラムに返されない場合は観測できません。
これはWeakMapのキーやWeakSetのメンバー、FinalizationRegistry セルレコードの[[WeakRefTarget]] や[[UnregisterToken]] フィールドにも当てはまります。
上記定義は、WeakMapのキーがライブでない場合、その対応する値も必ずしもライブでないことを意味します。
注6
ライブネスは、エンジンが空にしてはならない
WeakRef の下限です。ここで定義されるライブネスは決定不能です。実際には、エンジンは到達可能性などの保守的な近似を使用します。実装には大きな裁量が期待されます。
9.9.3 実行
任意の時点で、オブジェクトやシンボルの集合S がライブ でない場合、ECMAScript実装は次の手順をアトミックに実行することができます:
S の各要素value について、次を行う
ref .[[WeakRefTarget]] がvalue であるWeakRef
ref それぞれについて、次を行う
ref .[[WeakRefTarget]] をempty に設定する。
fg .[[Cells]] に、cell .[[WeakRefTarget]] がvalue であるRecord
cell を含むFinalizationRegistry
fg それぞれについて、次を行う
cell .[[WeakRefTarget]] をempty に設定する。
必要に応じてHostEnqueueFinalizationRegistryCleanupJob (fg )を実行する。
map .[[WeakMapData]] に、r .[[Key]] がvalue であるRecord
r を含むWeakMap map それぞれについて、次を行う
r .[[Key]] をempty に設定する。
r .[[Value]] をempty に設定する。
set .[[WeakSetData]] にvalue を含むWeakSet
set それぞれについて、次を行う
set .[[WeakSetData]] 内の値がvalue である要素を、値がempty である要素に置き換える。
注1
ライブネスの定義と合わせて、この節はWeakRef に関する実装最適化を規定します。
オブジェクトの識別性を観測せずにアクセスすることは可能です。逃避しないオブジェクトのプロパティへのスカラ置換やデッドバリアブル除去など、識別性が観測されない場合の最適化は許されます。従って、そのようなオブジェクトを指すWeakRef が観測的に空になることは許されます。
一方、オブジェクトの識別性が観測され、そのオブジェクトがWeakRef の[[WeakRefTarget]] 内部スロットにある場合、観測的にWeakRef を空にするような再素材化などの最適化は許されません。
HostEnqueueFinalizationRegistryCleanupJob の呼び出しは任意であるため、FinalizationRegistry に登録されたオブジェクトは必ずしもそのFinalizationRegistry をライブ にするとは限りません。たとえばFinalizationRegistry 自身が死んだ場合や、アプリケーションがシャットダウン中の場合など、どのような理由でもコールバックを省略できます。
注2
実装は、非ライブ なオブジェクトやシンボルの極大集合すべてについてWeakRef を空にする義務はありません。
実装がライブ でない集合S を選んでWeakRef を空にする場合、この定義はS 内のすべての値に対するWeakRef を同時に空にすることを要求します。つまり、実装がv を指すWeakRef だけを空にし、他のWeakRef は空にせず、その結果v の値が観測される可能性があるような実行が可能になる場合、それは非準拠です。
9.9.4 ホストフック
9.9.4.1 HostEnqueueFinalizationRegistryCleanupJob (
finalizationRegistry )
ホスト定義 抽象操作HostEnqueueFinalizationRegistryCleanupJobは、引数finalizationRegistry (FinalizationRegistry )を取り、unused を返します。
cleanupJob を、引数を取らずfinalizationRegistry をキャプチャし、呼び出されたときに次の手順を実行する新たなJob 抽象クロージャ とします:
cleanupResult をCompletion (CleanupFinalizationRegistry (finalizationRegistry ))とする。
もしcleanupResult がabrupt
completion であれば、エラー報告のためのホスト定義 の手順を実行する。
unused を返す。
HostEnqueueFinalizationRegistryCleanupJobの実装は、可能であればcleanupJob を将来のある時点で実行されるようスケジューリングします。また、9.5 の要件にも準拠しなければなりません。
9.10 ClearKeptObjects ( )
抽象操作ClearKeptObjectsは引数を取らず、unused を返します。ECMAScript実装は、ECMAScriptの同期的な実行列が完了した際にClearKeptObjectsを呼び出すことが期待されています。呼び出されたとき、次の手順を実行します:
agentRecord を周囲のエージェント のエージェントレコード とする。
agentRecord .[[KeptAlive]] を新たな空のList に設定する。
unused を返す。
9.11 AddToKeptObjects ( value )
抽象操作AddToKeptObjectsは引数value (オブジェクトまたはシンボル)を取り、unused を返します。呼び出されたとき、次の手順を実行します:
agentRecord を周囲のエージェント のエージェントレコード とする。
value をagentRecord .[[KeptAlive]] に追加する。
unused を返す。
注
AddToKeptObjects抽象操作が対象のオブジェクトまたはシンボルで呼び出されると、その対象を、
ClearKeptObjects が呼ばれるまで強参照で保持するリストに追加します。
9.12 CleanupFinalizationRegistry ( finalizationRegistry )
抽象操作CleanupFinalizationRegistryは引数finalizationRegistry (FinalizationRegistry )を取り、normal completion
containing unused またはthrow
completion のいずれかを返します。呼び出されたとき、次の手順を実行します:
保証 :finalizationRegistry は[[Cells]] および[[CleanupCallback]] 内部スロットを持つ。
callback をfinalizationRegistry .[[CleanupCallback]] とする。
finalizationRegistry .[[Cells]] に、cell .[[WeakRefTarget]] がempty であるRecord
cell が含まれている間、実装は次の手順を実行してもよい:
そのようなcell を任意に選択する。
cell をfinalizationRegistry .[[Cells]] から削除する。
? HostCallJobCallback (callback ,
undefined , « cell .[[HeldValue]] » ) を実行する。
unused を返す。
9.13 CanBeHeldWeakly ( v )
抽象操作CanBeHeldWeaklyは引数v (ECMAScript言語値 )を取り、Booleanを返します。v が弱参照として使用できる場合にのみtrue を返します。弱参照として使用できる値のみが、WeakMapのキー、WeakSetの要素、WeakRef のターゲット、またはFinalizationRegistry のターゲットのいずれかとなることができます。呼び出されたとき、次の手順を実行します:
もしv がオブジェクトである なら、true を返す。
もしv がシンボルである かつKeyForSymbol (v )がundefined であるなら、true を返す。
false を返す。
注
言語識別性 を持たない言語値は、事前の参照なしに現れることができ、弱参照として使用するのには適しません。Symbol.for で生成されたシンボル値は他のシンボル値と異なり、言語識別性を持たないため、弱参照として使用できません。ウェルノウンシンボル は通常ガベージコレクトされませんが、個数が限られておりさまざまな実装方法で管理可能であるため、弱参照として使用可能と見なされます。ただし、ライブ なWeakMap内のウェルノウンシンボルに関連付けられた値はガベージコレクトされにくく、実装によってはメモリリソースが「リーク」する可能性があります。
10 通常オブジェクトおよびエキゾチックオブジェクトの挙動
10.1 通常オブジェクトの内部メソッドと内部スロット
すべての通常オブジェクト は[[Prototype]] という内部スロットを持ちます。この内部スロットの値はnull またはオブジェクトであり、継承の実装に使用されます。プロパティ名P が通常オブジェクト O には存在しないが、その[[Prototype]] オブジェクトには存在する場合を考えます。P が[[Prototype]] オブジェクト上のデータプロパティ を指す場合、O はそれをgetアクセスのために継承し、あたかもP がO のプロパティであるかのようにふるまいます。P が[[Prototype]] オブジェクト上の書き込み可能なデータプロパティ を指す場合、O 上でのP へのsetアクセスは、O 上にP という名の新しいデータプロパティ を作成します。P が[[Prototype]] オブジェクト上の書き込み不可のデータプロパティ を指す場合、O 上でのP へのsetアクセスは失敗します。P が[[Prototype]] オブジェクト上のアクセサプロパティ を指す場合、そのアクセサはO によってgetアクセス・setアクセスの両方で継承されます。
すべての通常オブジェクト は、Boolean値を持つ[[Extensible]] 内部スロットを持ち、これは6.1.7.3 で規定される拡張性関連の内部メソッド不変条件を満たすために用いられます。すなわち、オブジェクトの[[Extensible]] 内部スロットの値がfalse に設定されると、そのオブジェクトにプロパティを追加したり、オブジェクトの[[Prototype]] 内部スロットの値を変更したり、[[Extensible]] を再びtrue に変更することはできなくなります。
以下のアルゴリズム記述では、O は通常オブジェクト 、P はプロパティキー 値、V は任意のECMAScript言語値 、Desc はプロパティディスクリプタ レコードとします。
各通常オブジェクト の内部メソッドは、同名の抽象操作に委譲されます。そのような抽象操作が他の内部メソッドに依存している場合、直接抽象操作を呼び出すのではなく、O 上でその内部メソッドが呼び出されます。このセマンティクスによって、エキゾチックオブジェクト が通常オブジェクト の内部メソッドを適用された際に、それらのオーバーライドされた内部メソッドが呼び出されることが保証されます。
10.1.1 [[GetPrototypeOf]] ( )
通常オブジェクト O の[[GetPrototypeOf]] 内部メソッドは引数を取らず、オブジェクトまたはnull を含むnormal
completion を返します。呼び出されたとき、次の手順を実行します:
OrdinaryGetPrototypeOf (O )を返す。
10.1.1.1 OrdinaryGetPrototypeOf ( O )
抽象操作OrdinaryGetPrototypeOfは引数O (オブジェクト)を取り、オブジェクトまたはnull を返します。呼び出されたとき、次の手順を実行します:
O .[[Prototype]] を返す。
10.1.2 [[SetPrototypeOf]] ( V )
通常オブジェクト O の[[SetPrototypeOf]] 内部メソッドは引数V (オブジェクトまたはnull )を取り、Booleanを含むnormal
completion を返します。呼び出されたとき、次の手順を実行します:
OrdinarySetPrototypeOf (O ,
V )を返す。
10.1.2.1 OrdinarySetPrototypeOf ( O , V )
抽象操作OrdinarySetPrototypeOfは引数O (オブジェクト)、V (オブジェクトまたはnull )を取り、Booleanを返します。呼び出されたとき、次の手順を実行します:
current をO .[[Prototype]] とする。
SameValue (V ,
current )がtrue なら、true を返す。
extensible をO .[[Extensible]] とする。
extensible がfalse なら、false を返す。
p をV とする。
done をfalse とする。
繰り返し、done がfalse の間、
p がnull なら、
done にtrue を設定する。
そうでなく、SameValue (p ,
O )がtrue なら、
false を返す。
それ以外の場合、
p .[[GetPrototypeOf]] が通常オブジェクト の10.1.1 で定義された内部メソッドでない場合、done にtrue を設定する。
それ以外の場合、p にp .[[Prototype]] を設定する。
O .[[Prototype]] にV を設定する。
true を返す。
注
7 のループは、[[GetPrototypeOf]] および[[SetPrototypeOf]] に通常オブジェクト 定義のみを使うオブジェクトのみから成るプロトタイプチェーンにサイクルが生じないことを保証します。
10.1.3 [[IsExtensible]] ( )
通常オブジェクト O の[[IsExtensible]] 内部メソッドは引数を取らず、Booleanを含むnormal
completion を返します。呼び出されたとき、次の手順を実行します:
OrdinaryIsExtensible (O )を返す。
10.1.3.1 OrdinaryIsExtensible ( O )
抽象操作OrdinaryIsExtensibleは引数O (オブジェクト)を取り、Booleanを返します。呼び出されたとき、次の手順を実行します:
O .[[Extensible]] を返す。
10.1.4 [[PreventExtensions]] ( )
通常オブジェクト O の[[PreventExtensions]] 内部メソッドは引数を取らず、true を含むnormal
completion を返します。呼び出されたとき、次の手順を実行します:
OrdinaryPreventExtensions (O )を返す。
10.1.4.1 OrdinaryPreventExtensions ( O )
抽象操作OrdinaryPreventExtensionsは引数O (オブジェクト)を取り、true を返します。呼び出されたとき、次の手順を実行します:
O .[[Extensible]] にfalse を設定する。
true を返す。
10.1.5 [[GetOwnProperty]] ( P )
通常オブジェクト O の[[GetOwnProperty]] 内部メソッドは引数P (プロパティキー )を取り、プロパティディスクリプタ またはundefined を含むnormal
completion を返します。呼び出されたとき、次の手順を実行します:
OrdinaryGetOwnProperty (O ,
P )を返す。
10.1.5.1 OrdinaryGetOwnProperty ( O , P )
抽象操作OrdinaryGetOwnPropertyは引数O (オブジェクト)、P (プロパティキー )を取り、プロパティディスクリプタ またはundefined を返します。呼び出されたとき、次の手順を実行します:
O がキーP の独自プロパティを持たない場合、undefined を返す。
D を新たなフィールドを持たないプロパティディスクリプタ として作成する。
X をキーP を持つO の独自プロパティとする。
X がデータプロパティ であれば、
D .[[Value]] にX の[[Value]] 属性の値を設定する。
D .[[Writable]] にX の[[Writable]] 属性の値を設定する。
そうでなければ、
保証 :X はアクセサプロパティ である。
D .[[Get]] にX の[[Get]] 属性の値を設定する。
D .[[Set]] にX の[[Set]] 属性の値を設定する。
D .[[Enumerable]] にX の[[Enumerable]] 属性の値を設定する。
D .[[Configurable]] にX の[[Configurable]] 属性の値を設定する。
D を返す。
10.1.6 [[DefineOwnProperty]] (
P , Desc )
通常オブジェクト O の[[DefineOwnProperty]] 内部メソッドは引数P (プロパティキー )、Desc (プロパティディスクリプタ )を取り、Booleanを含むnormal
completion またはthrow
completion を返します。呼び出されたとき、次の手順を実行します:
? OrdinaryDefineOwnProperty (O ,
P , Desc )を返す。
10.1.6.1 OrdinaryDefineOwnProperty ( O , P ,
Desc )
抽象操作OrdinaryDefineOwnPropertyは引数O (オブジェクト)、P (プロパティキー )、Desc (プロパティディスクリプタ )を取り、Booleanを含むnormal
completion またはthrow
completion を返します。呼び出されたとき、次の手順を実行します:
current を? O .[[GetOwnProperty]] (P )とする。
extensible を? IsExtensible (O )とする。
ValidateAndApplyPropertyDescriptor (O ,
P , extensible , Desc , current )を返す。
10.1.6.2 IsCompatiblePropertyDescriptor ( Extensible ,
Desc , Current )
抽象操作IsCompatiblePropertyDescriptorは引数Extensible (Boolean)、Desc (プロパティディスクリプタ )、Current (プロパティディスクリプタ またはundefined )を取り、Booleanを返します。呼び出されたとき、次の手順を実行します:
ValidateAndApplyPropertyDescriptor (undefined ,
"" , Extensible , Desc ,
Current )を返す。
10.1.6.3 ValidateAndApplyPropertyDescriptor ( O ,
P , extensible , Desc , current )
抽象操作ValidateAndApplyPropertyDescriptorは、引数O (オブジェクトまたはundefined )、P (プロパティキー )、extensible (Boolean)、Desc (プロパティディスクリプタ )、current (プロパティディスクリプタ またはundefined )を取り、Booleanを返す。Desc が指定されたextensibility と現在のプロパティcurrent のもとで、不変条件 を維持しつつ、オブジェクトのプロパティとして適用可能な場合に限り、true を返す。そのような適用が可能であり、かつO がundefined でない場合、プロパティ名P (必要に応じて新規作成)に対して実際に適用される。呼び出されたとき、次の手順を実行する:
保証 :P はプロパティキー である。
もしcurrent がundefined なら、
もしextensible がfalse なら、false を返す。
もしO がundefined なら、true を返す。
もしIsAccessorDescriptor (Desc )がtrue なら、
オブジェクトO にP という名前の独自のアクセサプロパティ を作成し、その[[Get]] 、[[Set]] 、[[Enumerable]] 、[[Configurable]] 属性を、Desc にそのフィールドがあればその値、なければ属性のデフォルト値 に設定する。
それ以外の場合、
オブジェクトO にP という名前の独自のデータプロパティ を作成し、その[[Value]] 、[[Writable]] 、[[Enumerable]] 、[[Configurable]] 属性を、Desc にそのフィールドがあればその値、なければ属性のデフォルト値 に設定する。
true を返す。
保証 :current は全てのフィールドが埋められたプロパティディスクリプタ である。
もしDesc がいかなるフィールドも持たないなら、true を返す。
もしcurrent .[[Configurable]] がfalse なら、
もしDesc が[[Configurable]] フィールドを持ち、かつDesc .[[Configurable]] がtrue なら、false を返す。
もしDesc が[[Enumerable]] フィールドを持ち、かつDesc .[[Enumerable]] がcurrent .[[Enumerable]] と異なるなら、false を返す。
もしIsGenericDescriptor (Desc )がfalse かつIsAccessorDescriptor (Desc )がIsAccessorDescriptor (current )と異なるなら、false を返す。
もしIsAccessorDescriptor (current )がtrue なら、
もしDesc が[[Get]] フィールドを持ち、かつSameValue (Desc .[[Get]] , current .[[Get]] )がfalse なら、false を返す。
もしDesc が[[Set]] フィールドを持ち、かつSameValue (Desc .[[Set]] , current .[[Set]] )がfalse なら、false を返す。
それ以外の場合、もしcurrent .[[Writable]] がfalse なら、
もしDesc が[[Writable]] フィールドを持ち、かつDesc .[[Writable]] がtrue なら、false を返す。
注:SameValue は、他の手段で区別できるNaN 値に対してもtrue を返す。ここで返すことで、O の既存プロパティが変更されないことを保証する。
もしDesc が[[Value]] フィールドを持つなら、SameValue (Desc .[[Value]] , current .[[Value]] )を返す。
もしO がundefined でないなら、
もしIsDataDescriptor (current )がtrue かつIsAccessorDescriptor (Desc )がtrue なら、
もしDesc が[[Configurable]] フィールドを持つならconfigurable をDesc .[[Configurable]] とし、なければcurrent .[[Configurable]] とする。
もしDesc が[[Enumerable]] フィールドを持つならenumerable をDesc .[[Enumerable]] とし、なければcurrent .[[Enumerable]] とする。
オブジェクトO のP という名前のプロパティを、[[Configurable]] 属性および[[Enumerable]] 属性をそれぞれconfigurable およびenumerable に、[[Get]] および[[Set]] 属性をDesc にそのフィールドがあればその値、なければ属性のデフォルト値 に設定したアクセサプロパティ で置き換える。
それ以外で、IsAccessorDescriptor (current )がtrue かつIsDataDescriptor (Desc )がtrue なら、
もしDesc が[[Configurable]] フィールドを持つならconfigurable をDesc .[[Configurable]] とし、なければcurrent .[[Configurable]] とする。
もしDesc が[[Enumerable]] フィールドを持つならenumerable をDesc .[[Enumerable]] とし、なければcurrent .[[Enumerable]] とする。
オブジェクトO のP という名前のプロパティを、[[Configurable]] 属性および[[Enumerable]] 属性をそれぞれconfigurable およびenumerable に、[[Value]] および[[Writable]] 属性をDesc にそのフィールドがあればその値、なければ属性のデフォルト値 に設定したデータプロパティ で置き換える。
それ以外の場合、
Desc の各フィールドについて、オブジェクトO のP という名前のプロパティの対応する属性にその値を設定する。
true を返す。
10.1.7 [[HasProperty]] ( P )
通常オブジェクト O の [[HasProperty]] 内部メソッドは、引数 P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
Return ? OrdinaryHasProperty (O ,
P ).
10.1.7.1 OrdinaryHasProperty ( O , P )
抽象操作 OrdinaryHasProperty は、引数 O (オブジェクト)と P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
hasOwn を ? O .[[GetOwnProperty]] (P ) とする。
もし hasOwn が undefined でなければ、true
を返す。
parent を ? O .[[GetPrototypeOf]] () とする。
もし parent が null でなければ、
Return ? parent .[[HasProperty]] (P )。
false を返す。
10.1.8 [[Get]] ( P ,
Receiver )
通常オブジェクト O の [[Get]] 内部メソッドは、引数 P (プロパティキー )および
Receiver (ECMAScript言語値 )を取り、normal completion
containing なECMAScript言語値 またはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
Return ? OrdinaryGet (O , P ,
Receiver ).
10.1.8.1 OrdinaryGet ( O , P ,
Receiver )
抽象操作 OrdinaryGet は、引数 O (オブジェクト)、P (プロパティキー )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なECMAScript言語値 またはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
desc を ? O .[[GetOwnProperty]] (P ) とする。
もし desc が undefined なら、
parent を ? O .[[GetPrototypeOf]] () とする。
もし parent が null
なら、undefined を返す。
Return ? parent .[[Get]] (P ,
Receiver )。
もし IsDataDescriptor (desc )
が true なら、desc .[[Value]] を返す。
保証 :IsAccessorDescriptor (desc )
が true である。
getter を desc .[[Get]] とする。
もし getter が undefined なら、undefined
を返す。
Return ? Call (getter ,
Receiver )。
10.1.9 [[Set]] ( P ,
V , Receiver )
通常オブジェクト O の [[Set]] 内部メソッドは、引数 P (プロパティキー )、V (ECMAScript言語値 )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
Return ? OrdinarySet (O , P ,
V , Receiver ).
10.1.9.1 OrdinarySet ( O , P , V ,
Receiver )
抽象操作 OrdinarySet は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript言語値 )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
ownDesc を ? O .[[GetOwnProperty]] (P ) とする。
Return ? OrdinarySetWithOwnDescriptor (O ,
P , V , Receiver , ownDesc )。
10.1.9.2 OrdinarySetWithOwnDescriptor ( O ,
P , V , Receiver , ownDesc )
抽象操作 OrdinarySetWithOwnDescriptor は、引数 O (オブジェクト)、P (プロパティキー )、V (ECMAScript言語値 )、Receiver (ECMAScript言語値 )、ownDesc (プロパティディスクリプタ またはundefined )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
もし ownDesc が undefined なら、
parent を ? O .[[GetPrototypeOf]] () とする。
もし parent が null でなければ、
Return ? parent .[[Set]] (P ,
V , Receiver )。
それ以外の場合、
ownDesc を PropertyDescriptor { [[Value]] : undefined ,
[[Writable]] : true , [[Enumerable]] : true ,
[[Configurable]] : true }
とする。
もし IsDataDescriptor (ownDesc )
が true なら、
もし ownDesc .[[Writable]] が
false なら、false を返す。
もし Receiver がオブジェクトでない なら、false
を返す。
existingDescriptor を ? Receiver .[[GetOwnProperty]] (P ) とする。
もし existingDescriptor が undefined でなければ、
もし IsAccessorDescriptor (existingDescriptor )
が true なら、false を返す。
もし existingDescriptor .[[Writable]] が false
なら、false を返す。
valueDesc を PropertyDescriptor { [[Value]] : V } とする。
Return ? Receiver .[[DefineOwnProperty]] (P ,
valueDesc )。
それ以外の場合、
保証 :Receiver は現在プロパティP を持たない。
Return ? CreateDataProperty (Receiver ,
P , V )。
保証 :IsAccessorDescriptor (ownDesc )
が true である。
setter を ownDesc .[[Set]] とする。
もし setter が undefined なら、false を返す。
? Call (setter ,
Receiver , « V ») を実行する。
true を返す。
10.1.10 [[Delete]] ( P )
通常オブジェクト O の [[Delete]] 内部メソッドは、引数 P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
Return ? OrdinaryDelete (O , P ).
10.1.10.1 OrdinaryDelete ( O , P )
抽象操作 OrdinaryDelete は、引数 O (オブジェクト)、P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
desc を ? O .[[GetOwnProperty]] (P ) とする。
もし desc が undefined なら、true を返す。
もし desc .[[Configurable]] が
true なら、
O から名前 P の独自プロパティを削除する。
true を返す。
false を返す。
10.1.11 [[OwnPropertyKeys]] ( )
通常オブジェクト O の [[OwnPropertyKeys]] 内部メソッドは、引数を取らず、normal completion
containing なList (プロパティキー のリスト)を返す。呼び出されたとき、次の手順を実行する:
Return OrdinaryOwnPropertyKeys (O ).
10.1.11.1 OrdinaryOwnPropertyKeys ( O )
抽象操作 OrdinaryOwnPropertyKeys は、引数 O (オブジェクト)を取り、List (プロパティキー のリスト)を返す。呼び出されたとき、次の手順を実行する:
keys を新たな空の List とする。
O の各独自プロパティキー P について、P が
配列インデックス である場合、昇順の数値インデックス順で、
P を keys に追加する。
O の各独自プロパティキー P について、P
が文字列 かつ配列インデックス でない場合、プロパティ作成の時系列で昇順に、
P を keys に追加する。
O の各独自プロパティキー P について、P
がシンボル である場合、プロパティ作成の時系列で昇順に、
P を keys に追加する。
keys を返す。
10.1.12 OrdinaryObjectCreate ( proto [ ,
additionalInternalSlotsList ] )
抽象操作 OrdinaryObjectCreate は、引数 proto (オブジェクトまたは null )および省略可能な
additionalInternalSlotsList (List :内部スロット名のリスト)を取り、オブジェクトを返す。これは新しい
通常オブジェクト
の実行時生成を指定するために使用される。additionalInternalSlotsList には、[[Prototype]] および [[Extensible]]
以外にオブジェクトの一部として定義されるべき追加の内部スロットの名前が含まれる。additionalInternalSlotsList が指定されていない場合、新たな空の
List
が使用される。呼び出されたとき、次の手順を実行する:
internalSlotsList を « [[Prototype]] , [[Extensible]] » とする。
もし additionalInternalSlotsList が存在するなら、internalSlotsList を
リスト結合 により internalSlotsList
と additionalInternalSlotsList の連結結果に設定する。
O を MakeBasicObject (internalSlotsList )
とする。
O .[[Prototype]] を proto に設定する。
O を返す。
注
OrdinaryObjectCreate は MakeBasicObject
を呼ぶ以外のことはほとんどしないが、その使用は 通常オブジェクト
を作る意図を伝える。したがって、本仕様内では、オブジェクトの内部メソッドを変更して結果が通常でなくなるようなアルゴリズムによっては呼び出されない。エキゾチックオブジェクト を生成する操作は MakeBasicObject を直接呼び出す。
10.1.13 OrdinaryCreateFromConstructor ( constructor ,
intrinsicDefaultProto [ , internalSlotsList ] )
抽象操作 OrdinaryCreateFromConstructor は、引数 constructor (関数オブジェクト )、intrinsicDefaultProto (文字列)、および省略可能な
internalSlotsList (List :内部スロット名のリスト)を取り、normal completion
containing なオブジェクトまたはthrow
completion のいずれかを返す。これは通常オブジェクト を生成し、その [[Prototype]] 値は constructor の "prototype"
プロパティから取得される(存在しない場合は intrinsicDefaultProto
で指定されたインストリンシックが使われる)。internalSlotsList
には、オブジェクトの一部として定義すべき追加の内部スロット名が含まれる。省略された場合、新たな空の List
が使われる。呼び出されたとき、次の手順を実行する:
保証 :intrinsicDefaultProto
はこの仕様のインストリンシックオブジェクト名であり、対応するオブジェクトはオブジェクトの [[Prototype]]
値として使用することを意図したインストリンシックでなければならない。
proto を ? GetPrototypeFromConstructor (constructor ,
intrinsicDefaultProto ) とする。
もし internalSlotsList が存在するなら、slotsList を
internalSlotsList とする。
それ以外の場合、slotsList を新たな空の List とする。
Return OrdinaryObjectCreate (proto ,
slotsList )。
10.1.14 GetPrototypeFromConstructor ( constructor ,
intrinsicDefaultProto )
抽象操作 GetPrototypeFromConstructor は、引数 constructor (関数オブジェクト )、intrinsicDefaultProto (文字列)を取り、normal completion
containing なオブジェクトまたはthrow
completion のいずれかを返す。これは、特定のconstructor に対応するオブジェクトを生成する際に使うべき [[Prototype]] 値を判定する。値は constructor の "prototype"
プロパティから取得される。存在しない場合は intrinsicDefaultProto で指定されたインストリンシックが使われる。呼び出されたとき、次の手順を実行する:
保証 :intrinsicDefaultProto
はこの仕様のインストリンシックオブジェクト名であり、対応するオブジェクトはオブジェクトの [[Prototype]]
値として使用することを意図したインストリンシックでなければならない。
proto を ? Get (constructor ,
"prototype" ) とする。
もし proto がオブジェクトでない なら、
realm を ? GetFunctionRealm (constructor )
とする。
proto を realm の intrinsicDefaultProto
という名前のインストリンシックオブジェクトに設定する。
proto を返す。
注
constructor が [[Prototype]] 値を提供しない場合、使用されるデフォルト値は
constructor 関数の realm から取得され、実行中の実行コンテキスト からは取得されない。
10.1.15 RequireInternalSlot ( O , internalSlot
)
抽象操作RequireInternalSlotは、引数O (ECMAScript言語値 )およびinternalSlot (内部スロット名)を取り、normal completion
containing なunused またはthrow
completion のいずれかを返す。O がオブジェクトであり 、かつ指定された内部スロットを持たない場合、例外をスローする。呼び出されたとき、次の手順を実行する:
もしO がオブジェクトでない なら、TypeError 例外をスローする。
もしO がinternalSlot 内部スロットを持たないなら、TypeError 例外をスローする。
unused を返す。
10.2 ECMAScript関数オブジェクト
ECMAScriptの関数オブジェクト は、レキシカル環境に閉じたパラメータ付きのECMAScriptコードをカプセル化し、そのコードの動的な評価をサポートします。ECMAScriptの関数オブジェクト は通常オブジェクト であり、他の通常オブジェクト と同じ内部スロットおよび内部メソッドを持ちます。ECMAScriptの関数オブジェクト のコードは、厳格モードコード (11.2.2 )または非厳格コード のいずれかです。ECMAScriptの関数オブジェクト で、そのコードが厳格モードコード であるものをstrict関数 と呼びます。コードが厳格モードコード でないものをnon-strict関数 と呼びます。
[[Extensible]] および[[Prototype]] に加え、ECMAScript関数オブジェクト は表30 に示す内部スロットも持ちます。
表30: ECMAScript関数オブジェクトの内部スロット
すべてのECMAScript関数オブジェクト は、ここで定義される[[Call]] 内部メソッドを持っています。また、コンストラクタ でもあるECMAScript関数は、さらに[[Construct]] 内部メソッドも持ちます。
10.2.1 [[Call]] ( thisArgument ,
argumentsList )
ECMAScriptの関数オブジェクト F の[[Call]] 内部メソッドは、引数thisArgument (ECMAScript言語値 )およびargumentsList (List (要素はECMAScript言語値 ))を取り、normal completion
containing なECMAScript言語値 またはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
callerContext を実行中の実行コンテキスト とする。
calleeContext をPrepareForOrdinaryCall (F ,
undefined )とする。
保証 :calleeContext は現在実行中の実行コンテキスト である。
もしF .[[IsClassConstructor]] がtrue なら、
error を新しく生成したTypeError オブジェクトとする。
注:error はcalleeContext 内で、F に関連付けられたRealm
Record で作成される。
calleeContext を実行コンテキストスタック から除去し、callerContext を実行中の実行コンテキスト として復元する。
ThrowCompletion (error )を返す。
OrdinaryCallBindThis (F ,
calleeContext , thisArgument )を実行する。
result をCompletion (OrdinaryCallEvaluateBody (F ,
argumentsList ))とする。
calleeContext を実行コンテキストスタック から除去し、callerContext を実行中の実行コンテキスト として復元する。
もしresult がreturn
completion なら、result .[[Value]] を返す。
保証 :result はthrow
completion である。
? result を返す。
注
ステップ7 でcalleeContext が実行コンテキストスタック から除去される際、そのコンテキストがサスペンドされ、アクセス可能なGeneratorによって後で再開されるために保持されているのであれば、破棄されてはならない。
10.2.1.1 PrepareForOrdinaryCall ( F ,
newTarget )
抽象操作PrepareForOrdinaryCallは、引数F (ECMAScript関数オブジェクト )、newTarget (オブジェクトまたはundefined )を取り、実行コンテキスト を返す。呼び出されたとき、次の手順を実行する:
callerContext を実行中の実行コンテキスト とする。
calleeContext を新しいECMAScriptコード実行コンテキスト とする。
calleeContext のFunctionをF に設定する。
calleeRealm をF .[[Realm]] とする。
calleeContext のRealm をcalleeRealm に設定する。
calleeContext のScriptOrModuleをF .[[ScriptOrModule]] に設定する。
localEnv をNewFunctionEnvironment (F ,
newTarget )とする。
calleeContext のLexicalEnvironmentをlocalEnv に設定する。
calleeContext のVariableEnvironmentをlocalEnv に設定する。
calleeContext のPrivateEnvironmentをF .[[PrivateEnvironment]] に設定する。
もしcallerContext がすでにサスペンドされていなければ、callerContext をサスペンドする。
calleeContext を実行コンテキストスタック にプッシュする;calleeContext は現在の実行中の実行コンテキスト である。
注:この時点以降に生成される例外オブジェクトはcalleeRealm に関連付けられる。
calleeContext を返す。
10.2.1.2 OrdinaryCallBindThis ( F ,
calleeContext , thisArgument )
抽象操作OrdinaryCallBindThisは、引数F (ECMAScript関数オブジェクト )、calleeContext (実行コンテキスト )、thisArgument (ECMAScript言語値 )を取り、unused を返す。呼び出されたとき、次の手順を実行する:
thisMode をF .[[ThisMode]] とする。
もしthisMode がlexical なら、unused を返す。
calleeRealm をF .[[Realm]] とする。
localEnv をcalleeContext のLexicalEnvironmentとする。
もしthisMode がstrict なら、
thisValue をthisArgument とする。
それ以外の場合、
もしthisArgument がundefined またはnull のいずれかなら、
globalEnv をcalleeRealm .[[GlobalEnv]] とする。
保証 :globalEnv はグローバル環境レコード である。
thisValue をglobalEnv .[[GlobalThisValue]] とする。
それ以外の場合、
thisValue を! ToObject (thisArgument )とする。
注:ToObject はcalleeRealm を使ってラッパーオブジェクトを生成する。
保証 :localEnv は関数環境レコード である。
保証 :次のステップはlocalEnv .[[ThisBindingStatus]] がinitialized でないのでabrupt
completion を返すことはない。
! BindThisValue (localEnv ,
thisValue )を実行する。
unused を返す。
10.2.1.3 ランタイムセマンティクス: EvaluateBody
構文指示操作 EvaluateBodyは、引数functionObject (ECMAScript関数オブジェクト )、argumentsList (List (要素はECMAScript言語値 ))を取り、return
completion またはthrow
completion を返す。以下の生成規則ごとに定義される:
FunctionBody :
FunctionStatementList
? EvaluateFunctionBody of FunctionBody
を、引数functionObject およびargumentsList で呼び出して返す。
ConciseBody :
ExpressionBody
? EvaluateConciseBody of ConciseBody
を、引数functionObject およびargumentsList で呼び出して返す。
GeneratorBody :
FunctionBody
? EvaluateGeneratorBody of GeneratorBody
を、引数functionObject およびargumentsList で呼び出して返す。
AsyncGeneratorBody
: FunctionBody
? EvaluateAsyncGeneratorBody of AsyncGeneratorBody
を、引数functionObject およびargumentsList で呼び出して返す。
AsyncFunctionBody
: FunctionBody
? EvaluateAsyncFunctionBody of AsyncFunctionBody
を、引数functionObject およびargumentsList で呼び出して返す。
AsyncConciseBody
: ExpressionBody
? EvaluateAsyncConciseBody of AsyncConciseBody
を、引数functionObject およびargumentsList で呼び出して返す。
Initializer :
=
AssignmentExpression
保証 :argumentsList は空である。
保証 :functionObject .[[ClassFieldInitializerName]] はempty でない。
もしIsAnonymousFunctionDefinition (AssignmentExpression )がtrue なら、
value を? NamedEvaluation of Initializer
を、引数functionObject .[[ClassFieldInitializerName]] で呼び出して得る。
それ以外の場合、
rhs を? Evaluation
of AssignmentExpression
で呼び出して得る。
value を? GetValue (rhs )で得る。
ReturnCompletion (value )を返す。
注
フィールド初期化子は関数境界を構成するが、FunctionDeclarationInstantiation を呼び出しても観測可能な効果はないため省略される。
ClassStaticBlockBody
: ClassStaticBlockStatementList
保証 :argumentsList は空である。
? EvaluateClassStaticBlockBody of ClassStaticBlockBody
を引数functionObject で呼び出して返す。
10.2.1.4 OrdinaryCallEvaluateBody ( F ,
argumentsList )
抽象操作OrdinaryCallEvaluateBodyは引数F (ECMAScript関数オブジェクト )、argumentsList (List (要素はECMAScript言語値 ))を取り、return
completion またはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
? EvaluateBody of F .[[ECMAScriptCode]]
を、引数F およびargumentsList で呼び出して返す。
10.2.2 [[Construct]] (
argumentsList , newTarget )
ECMAScriptの関数オブジェクト F の[[Construct]] 内部メソッドは、引数argumentsList (List (要素はECMAScript言語値 ))、newTarget (コンストラクタ )を取り、normal completion
containing なオブジェクトまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
callerContext を実行中の実行コンテキスト とする。
kind をF .[[ConstructorKind]] とする。
もしkind がbase なら、
thisArgument を? OrdinaryCreateFromConstructor (newTarget ,
"%Object.prototype%" )とする。
calleeContext をPrepareForOrdinaryCall (F ,
newTarget )とする。
保証 :calleeContext は現在実行中の実行コンテキスト である。
もしkind がbase なら、
OrdinaryCallBindThis (F ,
calleeContext , thisArgument )を実行する。
initializeResult をCompletion (InitializeInstanceElements (thisArgument ,
F ))とする。
もしinitializeResult がabrupt
completion なら、
calleeContext を実行コンテキストスタック から除去し、callerContext を実行中の実行コンテキスト として復元する。
? initializeResult を返す。
constructorEnv をcalleeContext のLexicalEnvironmentとする。
result をCompletion (OrdinaryCallEvaluateBody (F ,
argumentsList ))とする。
calleeContext を実行コンテキストスタック から除去し、callerContext を実行中の実行コンテキスト として復元する。
もしresult がthrow
completion なら、
? result を返す。
保証 :result はreturn
completion である。
もしresult .[[Value]] がオブジェクトである なら、result .[[Value]] を返す。
もしkind がbase なら、thisArgument を返す。
もしresult .[[Value]] がundefined でないなら、TypeError 例外をスローする。
thisBinding を? constructorEnv .GetThisBinding()とする。
保証 :thisBinding はオブジェクトである 。
thisBinding を返す。
10.2.3 OrdinaryFunctionCreate ( functionPrototype ,
sourceText , ParameterList , Body , thisMode ,
env , privateEnv )
抽象操作OrdinaryFunctionCreateは、引数functionPrototype (オブジェクト)、sourceText (Unicodeコードポイント列)、ParameterList (Parse
Node )、Body (Parse
Node )、thisMode (lexical-this またはnon-lexical-this )、env (Environment
Record )、privateEnv (PrivateEnvironment
Record またはnull )を取り、ECMAScript関数オブジェクト を返す。この操作は、デフォルトの[[Call]] 内部メソッドを持ち、[[Construct]] 内部メソッドを持たない(ただしMakeConstructor などの操作で後から追加される場合がある)新しい関数の実行時生成を規定するものである。sourceText は生成される関数の構文定義のソーステキストである。呼び出されたとき、次の手順を実行する:
internalSlotsList を表30 に示す内部スロットとする。
F をOrdinaryObjectCreate (functionPrototype ,
internalSlotsList )とする。
F .[[Call]] を10.2.1 で規定される定義に設定する。
F .[[SourceText]] をsourceText に設定する。
F .[[FormalParameters]] をParameterList に設定する。
F .[[ECMAScriptCode]] をBody に設定する。
Strict をIsStrict (Body )とする。
F .[[Strict]] をStrict に設定する。
もしthisMode がlexical-this なら、F .[[ThisMode]] をlexical に設定する。
それ以外でStrict がtrue なら、F .[[ThisMode]] をstrict に設定する。
それ以外の場合、F .[[ThisMode]] をglobal に設定する。
F .[[IsClassConstructor]] をfalse に設定する。
F .[[Environment]] をenv に設定する。
F .[[PrivateEnvironment]] をprivateEnv に設定する。
F .[[ScriptOrModule]] をGetActiveScriptOrModule ()に設定する。
F .[[Realm]] を現在のRealm Record に設定する。
F .[[HomeObject]] をundefined に設定する。
F .[[Fields]] を新たな空のList に設定する。
F .[[PrivateMethods]] を新たな空のList に設定する。
F .[[ClassFieldInitializerName]] をempty に設定する。
len をExpectedArgumentCount
of ParameterList とする。
SetFunctionLength (F ,
len )を実行する。
F を返す。
10.2.4 AddRestrictedFunctionProperties ( F ,
realm )
抽象操作AddRestrictedFunctionPropertiesは、引数F (関数オブジェクト )、realm (Realm
Record )を取り、unused を返す。呼び出されたとき、次の手順を実行する:
保証 :realm .[[Intrinsics]] .[[%ThrowTypeError% ]]が存在し初期化されている。
thrower をrealm .[[Intrinsics]] .[[%ThrowTypeError% ]]とする。
! DefinePropertyOrThrow (F ,
"caller" , PropertyDescriptor { [[Get]] :
thrower , [[Set]] : thrower , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
! DefinePropertyOrThrow (F ,
"arguments" , PropertyDescriptor { [[Get]] :
thrower , [[Set]] : thrower , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
unused を返す。
10.2.4.1 %ThrowTypeError% ( )
この関数は%ThrowTypeError% 固有オブジェクトである。
これは各realm ごとに一度だけ定義される匿名の組み込み関数オブジェクト である。
呼び出されたとき、次の手順を実行する:
TypeError 例外をスローする。
この関数の[[Extensible]] 内部スロットの値はfalse である。
この関数の"length" プロパティの属性は { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false } である。
この関数の"name" プロパティの属性は { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false } である。
10.2.5 MakeConstructor ( F [ ,
writablePrototype [ , prototype ] ] )
抽象操作MakeConstructorは、引数F (ECMAScript関数オブジェクト または組み込み関数オブジェクト )、省略可能なwritablePrototype (Boolean)、prototype (オブジェクト)を取り、unused を返す。F をコンストラクタ に変換する。呼び出されたとき、次の手順を実行する:
もしF がECMAScript関数オブジェクト なら、
保証 :IsConstructor (F )はfalse 。
保証 :F は拡張可能なオブジェクトであり、かつ"prototype" 独自プロパティを持たない。
F .[[Construct]] を10.2.2 で規定される定義に設定する。
それ以外の場合、
F .[[Construct]] を10.3.2 で規定される定義に設定する。
F .[[ConstructorKind]] をbase に設定する。
もしwritablePrototype が指定されていなければ、writablePrototype をtrue に設定する。
もしprototype が指定されていなければ、
prototype をOrdinaryObjectCreate (%Object.prototype% )に設定する。
! DefinePropertyOrThrow (prototype ,
"constructor" , PropertyDescriptor { [[Value]] : F , [[Writable]] : writablePrototype , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] :
writablePrototype , [[Enumerable]] :
false , [[Configurable]] :
false }) を実行する。
unused を返す。
10.2.6 MakeClassConstructor ( F )
抽象操作MakeClassConstructorは、引数F (ECMAScript関数オブジェクト )を取り、unused を返す。呼び出されたとき、次の手順を実行する:
保証 :F .[[IsClassConstructor]] はfalse である。
F .[[IsClassConstructor]] をtrue に設定する。
unused を返す。
10.2.7 MakeMethod ( F , homeObject )
抽象操作MakeMethodは、引数F (ECMAScript関数オブジェクト )、homeObject (オブジェクト)を取り、unused を返す。これはF をメソッドとして設定する。呼び出されたとき、次の手順を実行する:
保証 :homeObject は通常オブジェクト である。
F .[[HomeObject]] をhomeObject に設定する。
unused を返す。
10.2.8 DefineMethodProperty ( homeObject , key ,
closure , enumerable )
抽象操作DefineMethodPropertyは、引数homeObject (オブジェクト)、key (プロパティキー またはPrivate
Name )、closure (関数オブジェクト )、enumerable (Boolean)を取り、normal completion
containing なPrivateElement またはunused 、あるいはabrupt
completion を返す。呼び出されたとき、次の手順を実行する:
保証 :homeObject は通常かつ拡張可能なオブジェクトである。
もしkey がPrivate Name なら、
PrivateElement
{ [[Key]] : key , [[Kind]] : method , [[Value]] : closure } を返す。
それ以外の場合、
desc をPropertyDescriptor { [[Value]] :
closure , [[Writable]] :
true , [[Enumerable]] :
enumerable , [[Configurable]] :
true } とする。
? DefinePropertyOrThrow (homeObject ,
key , desc )を実行する。
注:DefinePropertyOrThrow がabrupt
completion を返すのは、クラスstaticメソッドでkey が"prototype" の場合のみである。
unused を返す。
10.2.9 SetFunctionName ( F , name [ ,
prefix ] )
抽象操作SetFunctionNameは、引数F (関数オブジェクト )、name (プロパティキー またはPrivate
Name )、省略可能なprefix (文字列)を取り、unused を返す。これはF に"name" プロパティを追加する。呼び出されたとき、次の手順を実行する:
保証 :F は拡張可能なオブジェクトであり、"name" 独自プロパティを持たない。
もしname がシンボルである なら、
description をname の[[Description]] 値とする。
もしdescription がundefined なら、name を空文字列に設定する。
それ以外の場合、name を文字列連結 で"[" 、description 、"]" を連結したものに設定する。
それ以外でname がPrivate Name なら、
name をname .[[Description]] に設定する。
もしF が[[InitialName]] 内部スロットを持つなら、
F .[[InitialName]] をname に設定する。
もしprefix が指定されているなら、
name を文字列連結 でprefix 、コード単位0x0020(SPACE)、name を連結したものに設定する。
もしF が[[InitialName]] 内部スロットを持つなら、
(任意で)F .[[InitialName]] をname に設定してもよい。
! DefinePropertyOrThrow (F ,
"name" , PropertyDescriptor { [[Value]] :
name , [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
unused を返す。
10.2.10 SetFunctionLength ( F , length )
抽象操作SetFunctionLengthは、引数F (関数オブジェクト )、length (非負の整数 または+∞)を取り、unused を返す。これはF に"length" プロパティを追加する。呼び出されたとき、次の手順を実行する:
保証 :F は拡張可能なオブジェクトであり、"length" 独自プロパティを持たない。
! DefinePropertyOrThrow (F ,
"length" , PropertyDescriptor { [[Value]] :
𝔽 (length ),
[[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
unused を返す。
10.2.11 FunctionDeclarationInstantiation ( func ,
argumentsList )
抽象操作FunctionDeclarationInstantiationは、引数func (ECMAScript関数オブジェクト )、argumentsList (List (要素はECMAScript言語値 ))を取り、normal completion
containing なunused またはthrow
completion を返す。func は関数オブジェクト であり、その実行コンテキスト が確立されつつある。
注1
ECMAScript関数の評価のために実行コンテキスト が確立されるとき、新しい関数環境レコード が作成され、その環境レコード 内で各仮引数の束縛がインスタンス化される。関数本体内の各宣言もインスタンス化される。もし関数の仮引数にデフォルト値初期化子が含まれていない場合、パラメータと本体宣言は同じ環境レコード でインスタンス化される。デフォルト値パラメータ初期化子が存在する場合は、本体宣言のための2つ目の環境レコード が作成される。仮引数と関数はFunctionDeclarationInstantiationの一部として初期化される。他の全ての束縛は関数本体の評価時に初期化される。
呼び出されたとき、次の手順を実行する:
calleeContext を実行中の実行コンテキスト とする。
code をfunc .[[ECMAScriptCode]] とする。
strict をfunc .[[Strict]] とする。
formals をfunc .[[FormalParameters]] とする。
parameterNames をBoundNames of
formals とする。
もしparameterNames に重複があれば、hasDuplicates をtrue 、なければfalse とする。
simpleParameterList をIsSimpleParameterList
of formals とする。
hasParameterExpressions をContainsExpression
of formals とする。
varNames をVarDeclaredNames of
code とする。
varDeclarations をVarScopedDeclarations
of code とする。
lexicalNames をLexicallyDeclaredNames
of code とする。
functionNames を新しい空のList とする。
functionsToInitialize を新しい空のList とする。
varDeclarations の各要素d について、逆順で、以下を行う:
もしd がVariableDeclaration でもForBinding でもBindingIdentifier でもない場合、
保証 :d はFunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、またはAsyncGeneratorDeclaration のいずれかである。
fn をBoundNames
of d の唯一の要素とする。
もしfunctionNames がfn を含まないなら、
fn をfunctionNames の先頭に挿入する。
注:同じ名前の関数宣言が複数ある場合、最後の宣言が使用される。
d をfunctionsToInitialize の先頭に挿入する。
argumentsObjectNeeded をtrue とする。
もしfunc .[[ThisMode]] がlexical なら、
注:アロー関数はargumentsオブジェクトを持たない。
argumentsObjectNeeded をfalse に設定する。
それ以外でparameterNames が"arguments" を含む場合、
argumentsObjectNeeded をfalse に設定する。
それ以外でhasParameterExpressions がfalse の場合、
もしfunctionNames が"arguments" を含むかlexicalNames が"arguments" を含むなら、
argumentsObjectNeeded をfalse に設定する。
もしstrict がtrue またはhasParameterExpressions がfalse なら、
注:パラメータ用には1つの環境レコード だけが必要。strictモードコード内でのevalの呼び出しは、そのevalの外側で見える新しい束縛を作成できないため。
env をcalleeContext のLexicalEnvironmentとする。
それ以外の場合、
注:仮引数リスト内のdirect eval呼び出しで作成される束縛がパラメータ宣言環境の外側になるよう、別の環境レコード が必要となる。
calleeEnv をcalleeContext のLexicalEnvironmentとする。
env をNewDeclarativeEnvironment (calleeEnv )とする。
保証 :calleeContext のVariableEnvironmentとcalleeEnv は同じ環境レコード である。
calleeContext のLexicalEnvironmentをenv に設定する。
parameterNames の各文字列paramName について、以下を行う:
alreadyDeclared を! env .HasBinding(paramName )とする。
注:早期エラー により、重複パラメータ名はパラメータデフォルト値やrestパラメータを持たない非厳格関数 でのみ許される。
もしalreadyDeclared がfalse なら、
! env .CreateMutableBinding(paramName ,
false )を実行する。
もしhasDuplicates がtrue なら、
! env .InitializeBinding(paramName ,
undefined )を実行する。
もしargumentsObjectNeeded がtrue なら、
もしstrict がtrue またはsimpleParameterList がfalse なら、
ao をCreateUnmappedArgumentsObject (argumentsList )とする。
それ以外の場合、
注:マップドargumentsオブジェクトは、restパラメータやパラメータデフォルト値初期化子、分割代入パラメータを持たない非厳格関数 でのみ提供される。
ao をCreateMappedArgumentsObject (func ,
formals , argumentsList , env )とする。
もしstrict がtrue なら、
! env .CreateImmutableBinding("arguments" ,
false )を実行する。
注:strictモードコード では早期エラー により、この束縛への代入は試みられないため、そのミュータビリティは観測できない。
それ以外の場合、
! env .CreateMutableBinding("arguments" ,
false )を実行する。
! env .InitializeBinding("arguments" ,
ao )を実行する。
parameterBindings をlist-concatenation of
parameterNames と« "arguments" »とする。
それ以外の場合、
parameterBindings をparameterNames とする。
iteratorRecord をCreateListIteratorRecord (argumentsList )とする。
もしhasDuplicates がtrue なら、
usedEnv をundefined とする。
それ以外の場合、
usedEnv をenv とする。
注:次のステップは、式位置でReturnCompletion を返すことはできない。なぜならそのようなcompletionはYieldExpression の使用のみで発生しうるが、これは早期エラー規則(15.5.1 ,
15.6.1 )によってパラメータリスト内で禁止されている。
? IteratorBindingInitialization of
formals with arguments iteratorRecord and usedEnv を実行する。
もしhasParameterExpressions がfalse なら、
注:パラメータとトップレベルvarのためには1つの環境レコード だけが必要。
instantiatedVarNames をList parameterBindings のコピーとする。
varNames の各要素n について、
もしinstantiatedVarNames がn を含まないなら、
n をinstantiatedVarNames に追加する。
! env .CreateMutableBinding(n ,
false )を実行する。
! env .InitializeBinding(n ,
undefined )を実行する。
varEnv をenv とする。
それ以外の場合、
注:仮引数リスト内の式で作成されるクロージャが関数本体の宣言を見ることができないよう、別の環境レコード が必要。
varEnv をNewDeclarativeEnvironment (env )とする。
calleeContext のVariableEnvironmentをvarEnv に設定する。
instantiatedVarNames を新しい空のList とする。
varNames の各要素n について、
もしinstantiatedVarNames がn を含まないなら、
n をinstantiatedVarNames に追加する。
! varEnv .CreateMutableBinding(n ,
false )を実行する。
もしparameterBindings がn を含まないか、またはfunctionNames がn を含むなら、
initialValue をundefined とする。
それ以外の場合、
initialValue を!
env .GetBindingValue(n ,
false )とする。
! varEnv .InitializeBinding(n ,
initialValue )を実行する。
注:仮引数と同じ名前のvarは、初期状態で対応する初期化済みパラメータと同じ値を持つ。
注:付録B.3.2.1 がこの地点で追加のステップを挿入する。
もしstrict がfalse なら、
lexEnv をNewDeclarativeEnvironment (varEnv )とする。
注:非厳格関数 はトップレベルのレキシカル宣言のために別の環境レコード を使う。こうすることでdirect
eval がevalコードで導入されたvarスコープ宣言が既存のトップレベルレキシカルスコープ宣言と衝突するかどうか判定できる。これはstrict関数 では不要であり、strictなdirect
eval は常に全ての宣言を新しい環境レコード に配置するためである。
それ以外の場合、
lexEnv をvarEnv とする。
calleeContext のLexicalEnvironmentをlexEnv に設定する。
lexDeclarations をLexicallyScopedDeclarations
of code とする。
lexDeclarations の各要素d について、以下を行う:
注:レキシカル宣言名は関数/ジェネレーター宣言、仮引数、var名と重複しない。レキシカル宣言名はここでインスタンス化されるが初期化はされない。
BoundNames of
d の各要素dn について、
もしIsConstantDeclaration
of d がtrue なら、
! lexEnv .CreateImmutableBinding(dn ,
true )を実行する。
それ以外の場合、
! lexEnv .CreateMutableBinding(dn ,
false )を実行する。
privateEnv をcalleeContext のPrivateEnvironmentとする。
functionsToInitialize の各Parse
Node f について、
fn をBoundNames of
f の唯一の要素とする。
fo をInstantiateFunctionObject
of f with arguments lexEnv とprivateEnv とする。
! varEnv .SetMutableBinding(fn , fo ,
false )を実行する。
unused を返す。
注2
B.3.2 は、ECMAScript
2015以前のWebブラウザ実装との後方互換性のために上記アルゴリズムへの拡張を提供する。
10.3 組み込み関数オブジェクト
組み込み関数オブジェクト は通常オブジェクト であり、通常オブジェクト について10.1 で規定された要件を満たさなければならない。
すべての通常オブジェクト に要求される内部スロット(10.1 参照)に加え、組み込み関数オブジェクト は次の内部スロットも持たなければならない:
組み込み関数オブジェクト の[[Prototype]] 内部スロットの初期値は、特に指定がない限り%Function.prototype% である。
組み込み関数オブジェクト は、10.3.1 の定義に準拠した[[Call]] 内部メソッドを持たなければならない。
組み込み関数オブジェクト は、そのオブジェクトが“コンストラクタ ”と記述されている場合、または本仕様のいずれかのアルゴリズムが明示的にその[[Construct]] 内部メソッドを設定する場合に限り、[[Construct]] 内部メソッドを持つ。そのような[[Construct]] 内部メソッドは10.3.2 の定義に準拠しなければならない。
実装は、本仕様で定義されていない追加の組み込み関数オブジェクト を提供してもよい。
10.3.1 [[Call]] ( thisArgument ,
argumentsList )
組み込み関数オブジェクト F の[[Call]] 内部メソッドは、引数thisArgument (ECMAScript言語値 )およびargumentsList (List (要素はECMAScript言語値 ))を取り、normal completion
containing なECMAScript言語値 またはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
? BuiltinCallOrConstruct (F ,
thisArgument , argumentsList , undefined )を返す。
10.3.2 [[Construct]] (
argumentsList , newTarget )
組み込み関数オブジェクト F (このメソッドが存在する場合)の[[Construct]] 内部メソッドは、引数argumentsList (List (要素はECMAScript言語値 ))、newTarget (コンストラクタ )を取り、normal completion
containing なオブジェクトまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
result を? BuiltinCallOrConstruct (F ,
uninitialized , argumentsList ,
newTarget )とする。
保証 :result はオブジェクトである 。
result を返す。
10.3.3 BuiltinCallOrConstruct ( F ,
thisArgument , argumentsList , newTarget )
抽象操作BuiltinCallOrConstructは、引数F (組み込み関数オブジェクト )、thisArgument (ECMAScript言語値 またはuninitialized )、argumentsList (List (要素はECMAScript言語値 ))、newTarget (コンストラクタ またはundefined )を取り、normal completion
containing なECMAScript言語値 またはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
callerContext を実行中の実行コンテキスト とする。
もしcallerContext がすでにサスペンドされていなければ、callerContext をサスペンドする。
calleeContext を新しい実行コンテキスト とする。
calleeContext のFunctionをF に設定する。
calleeRealm をF .[[Realm]] とする。
calleeContext のRealm をcalleeRealm に設定する。
calleeContext のScriptOrModuleをnull に設定する。
calleeContext に対して必要な実装依存 の初期化を実行する。
calleeContext を実行コンテキストスタック にプッシュする;calleeContext は現在の実行中の実行コンテキスト である。
result をCompletion
Record とし、「F を評価する」ことにより得られる。仕様で定めるように、thisArgument がuninitialized ならthis 値は初期化されない。それ以外の場合はthisArgument がthis 値となる。argumentsList は指定されたパラメータを与え、newTarget はNewTarget値を与える。
注:F が本ドキュメントで定義されている場合、「F の仕様」とは、ステップあるいはその他の手段で規定されるその挙動である。
calleeContext を実行コンテキストスタック から除去し、callerContext を実行中の実行コンテキスト として復元する。
? result を返す。
注
calleeContext が実行コンテキストスタック から除去される際、アクセス可能なGeneratorによってサスペンドされ再開のために保持されている場合は、破棄されてはならない。
10.3.4 CreateBuiltinFunction ( behaviour ,
length , name , additionalInternalSlotsList [ , realm
[ , prototype [ , prefix ] ] ] )
抽象操作CreateBuiltinFunctionは、引数behaviour (Abstract
Closure 、アルゴリズムステップの集合、または本仕様で与えられる関数の挙動の別の定義)、length (非負の整数 または+∞)、name (プロパティキー またはPrivate
Name )、additionalInternalSlotsList (List (内部スロット名))、省略可能なrealm (Realm
Record )、prototype (オブジェクトまたはnull )、prefix (文字列)を取り、組み込み関数オブジェクト を返す。additionalInternalSlotsList はそのオブジェクトの一部として定義すべき追加の内部スロット名を含む。この操作は組み込み関数オブジェクト を生成する。呼び出されたとき、次の手順を実行する:
もしrealm が指定されていなければ、realm を現在のRealm Record に設定する。
もしprototype が指定されていなければ、prototype をrealm .[[Intrinsics]] .[[%Function.prototype% ]]に設定する。
internalSlotsList をList とし、これから作成する組み込み関数オブジェクト に10.3 が要求するすべての内部スロット名を入れる。
internalSlotsList にadditionalInternalSlotsList の要素を追加する。
func を新しい組み込み関数オブジェクト とし、呼び出されたときbehaviour で規定された動作を、指定された引数をbehaviour で指定されたパラメータ値として用いて実行するものとする。新しい関数オブジェクト はinternalSlotsList の名前を持つ内部スロットと、[[InitialName]] 内部スロットを持つ。
func .[[Prototype]] をprototype に設定する。
func .[[Extensible]] をtrue に設定する。
func .[[Realm]] をrealm に設定する。
func .[[InitialName]] をnull に設定する。
SetFunctionLength (func ,
length )を実行する。
もしprefix が指定されていなければ、
SetFunctionName (func ,
name )を実行する。
それ以外の場合、
SetFunctionName (func ,
name , prefix )を実行する。
func を返す。
本仕様で定義される各組み込み関数は、CreateBuiltinFunction抽象操作の呼び出しにより生成される。
10.4 組み込みエキゾチックオブジェクトの内部メソッドとスロット
本仕様は複数の種類の組み込みエキゾチックオブジェクト を定義する。これらのオブジェクトは、特定の状況を除いて、一般的には通常オブジェクト と同様に振る舞う。以下のエキゾチックオブジェクト は、特に以下で明示的に規定されている場合を除き、通常オブジェクト の内部メソッドを使用する:
10.4.1 バウンド関数エキゾチックオブジェクト
バウンド関数エキゾチックオブジェクト は、別の関数オブジェクト をラップするエキゾチックオブジェクト である。バウンド関数エキゾチックオブジェクト は呼び出し可能([[Call]] 内部メソッドを持ち、[[Construct]] 内部メソッドを持つ場合もある)である。バウンド関数エキゾチックオブジェクト の呼び出しは、通常はラップされた関数の呼び出しとなる。
あるオブジェクトがバウンド関数エキゾチックオブジェクト であるのは、その[[Call]] および(該当する場合)[[Construct]] 内部メソッドが以下の実装を用い、それ以外の必須内部メソッドが10.1 で定義されているものを用いる場合である。これらのメソッドはBoundFunctionCreate で付与される。
バウンド関数エキゾチックオブジェクト は、表30 に挙げられているECMAScript関数オブジェクト の内部スロットは持たない。代わりに[[Prototype]] および[[Extensible]] に加え、表31 に挙げられている内部スロットを持つ。
表31: バウンド関数エキゾチックオブジェクトの内部スロット
内部スロット
型
説明
[[BoundTargetFunction]]
呼び出し可能オブジェクト
ラップされている関数オブジェクト 。
[[BoundThis]]
ECMAScript言語値
ラップされた関数を呼び出す際に常にthis 値として渡される値。
[[BoundArguments]]
List (要素はECMAScript言語値 )
ラップされた関数への呼び出しで最初の引数として使用される値のリスト。
10.4.1.1 [[Call]] (
thisArgument , argumentsList )
バウンド関数エキゾチックオブジェクト F の[[Call]] 内部メソッドは、引数thisArgument (ECMAScript言語値 )、argumentsList (List (要素はECMAScript言語値 ))を取り、normal completion
containing なECMAScript言語値 またはthrow
completion のいずれかを返す。呼び出されたとき、次の手順を実行する:
target をF .[[BoundTargetFunction]] とする。
boundThis をF .[[BoundThis]] とする。
boundArgs をF .[[BoundArguments]] とする。
args をlist-concatenation of
boundArgs とargumentsList とする。
? Call (target ,
boundThis , args )を返す。
10.4.1.2 [[Construct]] (
argumentsList , newTarget )
バウンド関数エキゾチックオブジェクト F の[[Construct]] 内部メソッドは、引数argumentsList (List (要素はECMAScript言語値 ))、newTarget (コンストラクタ )を取り、normal completion
containing なオブジェクトまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
target をF .[[BoundTargetFunction]] とする。
保証 :IsConstructor (target )はtrue である。
boundArgs をF .[[BoundArguments]] とする。
args をlist-concatenation of
boundArgs とargumentsList とする。
もしSameValue (F ,
newTarget )がtrue なら、newTarget をtarget とする。
? Construct (target ,
args , newTarget )を返す。
10.4.1.3 BoundFunctionCreate ( targetFunction ,
boundThis , boundArgs )
抽象操作BoundFunctionCreateは、引数targetFunction (関数オブジェクト )、boundThis (ECMAScript言語値 )、boundArgs (List (要素はECMAScript言語値 ))を取り、normal completion
containing な関数オブジェクト またはthrow
completion を返す。新しいバウンド関数エキゾチックオブジェクト の生成を規定する。呼び出されたとき、次の手順を実行する:
proto を? targetFunction .[[GetPrototypeOf]] ()とする。
internalSlotsList をlist-concatenation of « [[Prototype]] , [[Extensible]] »
および表31 に挙げられている内部スロットとする。
obj をMakeBasicObject (internalSlotsList )とする。
obj .[[Prototype]] をproto に設定する。
obj .[[Call]] を10.4.1.1 で説明されるものに設定する。
もしIsConstructor (targetFunction )がtrue なら、
obj .[[Construct]] を10.4.1.2 で説明されるものに設定する。
obj .[[BoundTargetFunction]] をtargetFunction に設定する。
obj .[[BoundThis]] をboundThis に設定する。
obj .[[BoundArguments]] をboundArgs に設定する。
obj を返す。
10.4.2 配列エキゾチックオブジェクト
配列(Array)は、配列インデックス プロパティキー (6.1.7 参照)に特別な扱いをするエキゾチックオブジェクト である。プロパティ名 が配列インデックス であるプロパティは要素 とも呼ばれる。すべての配列は、値が常に0以上の整数値(Number) で、その数学的値 が232 未満である"length" という非設定可能プロパティを持つ。"length" プロパティの値は、名前が配列インデックス であるすべての自身のプロパティ名よりも数値的に大きい;配列の自身のプロパティが作成または変更されるたびに、この不変条件を維持するために他のプロパティが必要に応じて調整される。具体的には、名前が配列インデックス である自身のプロパティが追加された場合、必要に応じて"length" プロパティの値はその配列インデックス の数値+1に変更される;また、"length" プロパティの値が変更された場合、新しいlength以上の値を持つ配列インデックス 名の自身のすべてのプロパティが削除される。この制約は配列の自身のプロパティにのみ適用され、プロトタイプから継承される"length" や配列インデックス プロパティには影響しない。
あるオブジェクトの[[DefineOwnProperty]] 内部メソッドが以下の実装を使い、それ以外の必須内部メソッドが10.1 で定義されているものを使う場合、そのオブジェクトは配列エキゾチックオブジェクト (単に「配列」)である。これらのメソッドはArrayCreate により付与される。
10.4.2.1 [[DefineOwnProperty]] (
P , Desc )
配列エキゾチックオブジェクト A の[[DefineOwnProperty]] 内部メソッドは、引数P (プロパティキー )、Desc (プロパティディスクリプタ )を受け取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしP が"length" なら、
? ArraySetLength (A ,
Desc )を返す。
それ以外でP が配列インデックス なら、
lengthDesc をOrdinaryGetOwnProperty (A ,
"length" )とする。
保証 :lengthDesc はundefined でない。
保証 :IsDataDescriptor (lengthDesc )はtrue 。
保証 :lengthDesc .[[Configurable]] はfalse 。
length をlengthDesc .[[Value]] とする。
保証 :length は0以上の整数値(Number) である。
index を! ToUint32 (P )とする。
もしindex ≥ length かつlengthDesc .[[Writable]] がfalse なら、false を返す。
succeeded を! OrdinaryDefineOwnProperty (A ,
P , Desc )とする。
もしsucceeded がfalse なら、false を返す。
もしindex ≥ length なら、
lengthDesc .[[Value]] をindex +
1 𝔽 に設定する。
succeeded を! OrdinaryDefineOwnProperty (A ,
"length" , lengthDesc )とする。
保証 :succeeded はtrue 。
true を返す。
? OrdinaryDefineOwnProperty (A ,
P , Desc )を返す。
10.4.2.2 ArrayCreate ( length [ , proto ]
)
抽象操作ArrayCreateは、引数length (0以上の整数 )、省略可能なproto (オブジェクト)を取り、normal completion
containing な配列エキゾチックオブジェクト またはthrow
completion を返す。これは新しい配列の生成を規定する。呼び出されたとき、次の手順を実行する:
もしlength > 232 - 1なら、RangeError 例外をスローする。
もしproto が指定されていなければ、proto を%Array.prototype% に設定する。
A をMakeBasicObject (« [[Prototype]] , [[Extensible]]
»)とする。
A .[[Prototype]] をproto に設定する。
A .[[DefineOwnProperty]] を10.4.2.1 で規定されるものに設定する。
! OrdinaryDefineOwnProperty (A ,
"length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false }) を実行する。
A を返す。
10.4.2.3 ArraySpeciesCreate ( originalArray ,
length )
抽象操作ArraySpeciesCreateは、引数originalArray (オブジェクト)、length (0以上の整数 )を取り、normal completion
containing なオブジェクトまたはthrow
completion を返す。これはoriginalArray に由来するコンストラクタ 関数を用いて新しい配列または類似オブジェクトを生成することを規定する。返されるオブジェクトが必ずしも配列であることは保証されない。呼び出されたとき、次の手順を実行する:
isArray を? IsArray (originalArray )とする。
もしisArray がfalse なら、? ArrayCreate (length )を返す。
C を? Get (originalArray ,
"constructor" )とする。
もしIsConstructor (C )がtrue なら、
thisRealm を現在のRealm Record とする。
realmC を? GetFunctionRealm (C )とする。
もしthisRealm とrealmC が同じRealm Record でないなら、
もしSameValue (C ,
realmC .[[Intrinsics]] .[[%Array% ]])がtrue なら、C をundefined に設定する。
もしC がオブジェクトである なら、
C を? Get (C , %Symbol.species% )に設定する。
もしC がnull なら、C をundefined に設定する。
もしC がundefined なら、? ArrayCreate (length )を返す。
もしIsConstructor (C )がfalse なら、TypeError 例外をスローする。
? Construct (C , « 𝔽 (length )
»)を返す。
注
もしoriginalArray が現在の実行中の実行コンテキスト のrealm とは異なるrealm の標準組み込みArrayコンストラクタ を使って生成されていた場合、新しい配列は実行中の実行コンテキスト のrealm で生成される。この仕様は、歴史的にArray.prototypeメソッドがArraySpeciesCreateで定義されるようになったWebブラウザとの互換性を維持する。
10.4.2.4 ArraySetLength ( A , Desc )
抽象操作ArraySetLengthは、引数A (配列)、Desc (プロパティディスクリプタ )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしDesc が[[Value]] フィールドを持たないなら、
! OrdinaryDefineOwnProperty (A ,
"length" , Desc )を返す。
newLenDesc をDesc のコピーとする。
newLen を? ToUint32 (Desc .[[Value]] )とする。
numberLen を? ToNumber (Desc .[[Value]] )とする。
もしSameValueZero (newLen ,
numberLen )がfalse なら、RangeError 例外をスローする。
newLenDesc .[[Value]] をnewLen に設定する。
oldLenDesc をOrdinaryGetOwnProperty (A ,
"length" )とする。
保証 :oldLenDesc はundefined でない。
保証 :IsDataDescriptor (oldLenDesc )はtrue 。
保証 :oldLenDesc .[[Configurable]] はfalse である。
oldLen をoldLenDesc .[[Value]] とする。
もしnewLen ≥ oldLen なら、
! OrdinaryDefineOwnProperty (A ,
"length" , newLenDesc )を返す。
もしoldLenDesc .[[Writable]] がfalse なら、false を返す。
もしnewLenDesc が[[Writable]] フィールドを持たないかnewLenDesc .[[Writable]] がtrue なら、
newWritable をtrue とする。
それ以外の場合、
注:[[Writable]] 属性をfalse に設定するのは、要素の削除に失敗した場合に遅延される。
newWritable をfalse とする。
newLenDesc .[[Writable]] をtrue に設定する。
succeeded を! OrdinaryDefineOwnProperty (A ,
"length" , newLenDesc )とする。
もしsucceeded がfalse なら、false を返す。
A のすべての自身のプロパティキー P について、P が配列インデックス かつ! ToUint32 (P ) ≥
newLen であるものを降順で、以下を行う:
deleteSucceeded を! A .[[Delete]] (P )とする。
もしdeleteSucceeded がfalse なら、
newLenDesc .[[Value]] を! ToUint32 (P ) +
1 𝔽 に設定する。
もしnewWritable がfalse なら、newLenDesc .[[Writable]] をfalse に設定する。
! OrdinaryDefineOwnProperty (A ,
"length" , newLenDesc )を実行する。
false を返す。
もしnewWritable がfalse なら、
succeeded を! OrdinaryDefineOwnProperty (A ,
"length" , PropertyDescriptor { [[Writable]] : false })とする。
保証 :succeeded はtrue である。
true を返す。
注
ステップ3 および4 では、Desc .[[Value]] がオブジェクトの場合、そのvalueOfメソッドが2回呼ばれる。これは第2版以降この仕様で定められているレガシーな挙動である。
10.4.3 文字列エキゾチックオブジェクト
Stringオブジェクトは、文字列値をカプセル化し、その文字列値の個々のコードユニット要素に対応する仮想の整数インデックス付き のデータプロパティ を公開するエキゾチックオブジェクト である。文字列エキゾチックオブジェクト は常に、カプセル化された文字列値の長さを値とするデータプロパティ
"length" を持つ。コードユニットのデータプロパティ と"length" プロパティは共に書き込み不可・設定不可である。
あるオブジェクトの[[GetOwnProperty]] 、[[DefineOwnProperty]] 、[[OwnPropertyKeys]] 内部メソッドが以下の実装を使い、それ以外の必須内部メソッドが10.1 で定義されているものを使う場合、そのオブジェクトは文字列エキゾチックオブジェクト (または単にStringオブジェクト)である。これらのメソッドはStringCreate によって付与される。
文字列エキゾチックオブジェクト は通常オブジェクト と同じ内部スロットを持つ。また、[[StringData]] 内部スロットを持つ。
10.4.3.1 [[GetOwnProperty]] (
P )
文字列エキゾチックオブジェクト S の[[GetOwnProperty]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なプロパティディスクリプタ またはundefined を返す。呼び出されたとき、次の手順を実行する:
desc をOrdinaryGetOwnProperty (S ,
P )とする。
もしdesc がundefined でなければ、desc を返す。
StringGetOwnProperty (S ,
P )を返す。
10.4.3.2 [[DefineOwnProperty]] (
P , Desc )
文字列エキゾチックオブジェクト S の[[DefineOwnProperty]] 内部メソッドは、引数P (プロパティキー )、Desc (プロパティディスクリプタ )を取り、normal completion
containing なBooleanを返す。呼び出されたとき、次の手順を実行する:
stringDesc をStringGetOwnProperty (S ,
P )とする。
もしstringDesc がundefined でなければ、
extensible をS .[[Extensible]] とする。
IsCompatiblePropertyDescriptor (extensible ,
Desc , stringDesc )を返す。
! OrdinaryDefineOwnProperty (S ,
P , Desc )を返す。
10.4.3.3 [[OwnPropertyKeys]] ( )
文字列エキゾチックオブジェクト O の[[OwnPropertyKeys]] 内部メソッドは引数を取らず、normal completion
containing なList (要素はプロパティキー )を返す。呼び出されたとき、次の手順を実行する:
keys を新しい空のList とする。
str をO .[[StringData]] とする。
保証 :str は文字列である 。
len をstr の長さとする。
0 ≤ i < len となる各整数 i について、昇順で:
! ToString (𝔽 (i ))をkeys に追加する。
O の自身のプロパティキー P について、P が配列インデックス かつ! ToIntegerOrInfinity (P )
≥ len であるものを昇順で:
P をkeys に追加する。
O の自身のプロパティキー P について、P が文字列である かつP が配列インデックス でないものを生成順に昇順で:
P をkeys に追加する。
O の自身のプロパティキー P について、P がシンボルである ものを生成順に昇順で:
P をkeys に追加する。
keys を返す。
10.4.3.4 StringCreate ( value , prototype )
抽象操作StringCreateは、引数value (文字列)、prototype (オブジェクト)を取り、文字列エキゾチックオブジェクト を返す。これは新しい文字列エキゾチックオブジェクト の生成を規定する。呼び出されたとき、次の手順を実行する:
S をMakeBasicObject (« [[Prototype]] , [[Extensible]] , [[StringData]] »)とする。
S .[[Prototype]] をprototype に設定する。
S .[[StringData]] をvalue に設定する。
S .[[GetOwnProperty]] を10.4.3.1 で規定されるものに設定する。
S .[[DefineOwnProperty]] を10.4.3.2 で規定されるものに設定する。
S .[[OwnPropertyKeys]] を10.4.3.3 で規定されるものに設定する。
length をvalue の長さとする。
! DefinePropertyOrThrow (S ,
"length" , PropertyDescriptor { [[Value]] : 𝔽 (length ), [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }) を実行する。
S を返す。
10.4.3.5 StringGetOwnProperty ( S , P )
抽象操作StringGetOwnPropertyは、引数S ([[StringData]] 内部スロットを持つオブジェクト)、P (プロパティキー )を取り、プロパティディスクリプタ またはundefined を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列でない なら、undefined を返す。
index をCanonicalNumericIndexString (P )とする。
もしindex が整数値(Number) でなければ、undefined を返す。
もしindex が-0 𝔽 またはindex <
-0 𝔽 なら、undefined を返す。
str をS .[[StringData]] とする。
保証 :str は文字列である 。
len をstr の長さとする。
もしℝ (index )
≥ len なら、undefined を返す。
resultStr をstr のsubstring (ℝ (index )からℝ (index )+1まで)とする。
プロパティディスクリプタ{ [[Value]] : resultStr , [[Writable]] : false , [[Enumerable]] : true , [[Configurable]] : false }を返す。
10.4.4 Argumentsエキゾチックオブジェクト
ほとんどのECMAScript関数は、コードで利用可能なargumentsオブジェクトを生成する。関数定義の特性によって、そのargumentsオブジェクトは通常オブジェクト またはargumentsエキゾチックオブジェクト のいずれかになる。argumentsエキゾチックオブジェクト は、エキゾチックオブジェクト であり、その配列インデックス プロパティは、関連付けられたECMAScript関数の呼び出しの仮引数束縛にマッピングされる。
オブジェクトが、ここで明示されていない内部メソッドについて10.1 で定義されたものを使い、指定された内部メソッドについて以下の実装を使う場合、そのオブジェクトはargumentsエキゾチックオブジェクト である。これらのメソッドはCreateMappedArgumentsObject で付与される。
注1
Argumentsエキゾチックオブジェクト は通常オブジェクト と同じ内部スロットを持つ。さらに[[ParameterMap]] 内部スロットを持つ。通常のargumentsオブジェクトも[[ParameterMap]] 内部スロットを持つが、その値は常にundefined である。通常のargumentsオブジェクトでは、このスロットはObject.prototype.toString(20.1.3.6 )によってのみ識別に利用される。
注2
argumentsエキゾチックオブジェクト の整数インデックス付き データプロパティ のうち、その数値名が対応する関数オブジェクト の仮引数の数より小さいものは、初期状態では関数の実行コンテキスト 内の対応する引数束縛と値を共有する。つまり、プロパティの値を変更すると、対応する引数束縛の値も変更され、その逆も同様である。この対応は、そのプロパティが削除されて再定義された場合や、アクセサープロパティに変更された場合に切れる。argumentsオブジェクトが通常オブジェクト である場合、プロパティの値は関数に渡された引数の単なるコピーであり、動的な連動はない。
注3
ParameterMapオブジェクトとそのプロパティ値は、argumentsオブジェクトと引数束縛の連動を規定するための仕組みとして用いられる。ParameterMapオブジェクトおよびそのプロパティ値となるオブジェクトは、ECMAScriptコードから直接観測できない。ECMAScript実装は、規定されたセマンティクスを実装するために実際にこれらのオブジェクトを生成・利用する必要はない。
注4
通常のargumentsオブジェクトは、アクセス時にTypeError 例外をスローする非設定可能なアクセサープロパティ "callee" を定義する。"callee" プロパティは、argumentsエキゾチックオブジェクト (一部の非厳格関数 でのみ生成される)ではより特別な意味を持つ。通常バリアントでこのプロパティを定義するのは、準拠ECMAScript実装によって他の方法で定義されないようにするためである。
注5
ECMAScript実装のargumentsエキゾチックオブジェクト には、歴史的にアクセサープロパティ の"caller" が含まれていた。ECMAScript
2017より前は、通常のargumentsオブジェクトにもthrowing"caller" アクセサを定義することが仕様で要求されていたが、現在はこの拡張は不要となった。
10.4.4.1 [[GetOwnProperty]] (
P )
argumentsエキゾチックオブジェクト args の[[GetOwnProperty]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なプロパティディスクリプタ またはundefined を返す。呼び出されたとき、次の手順を実行する:
desc をOrdinaryGetOwnProperty (args ,
P )とする。
もしdesc がundefined なら、undefined を返す。
map をargs .[[ParameterMap]] とする。
isMapped を! HasOwnProperty (map ,
P )とする。
もしisMapped がtrue なら、
desc .[[Value]] を! Get (map ,
P )に設定する。
desc を返す。
10.4.4.2 [[DefineOwnProperty]] (
P , Desc )
argumentsエキゾチックオブジェクト args の[[DefineOwnProperty]] 内部メソッドは、引数P (プロパティキー )、Desc (プロパティディスクリプタ )を取り、normal completion
containing なBooleanを返す。呼び出されたとき、次の手順を実行する:
map をargs .[[ParameterMap]] とする。
isMapped を! HasOwnProperty (map ,
P )とする。
newArgDesc をDesc とする。
もしisMapped がtrue かつIsDataDescriptor (Desc )がtrue なら、
もしDesc が[[Value]] フィールドを持たず、Desc が[[Writable]] フィールドを持ち、Desc .[[Writable]] がfalse なら、
newArgDesc をDesc のコピーとする。
newArgDesc .[[Value]] を! Get (map ,
P )に設定する。
allowed を! OrdinaryDefineOwnProperty (args ,
P , newArgDesc )とする。
もしallowed がfalse なら、false を返す。
もしisMapped がtrue なら、
もしIsAccessorDescriptor (Desc )がtrue なら、
! map .[[Delete]] (P )を実行する。
それ以外の場合、
もしDesc が[[Value]] フィールドを持つなら、
保証 :argumentsオブジェクトでマッピングされる仮引数は常に書き込み可能なので、次のSetは必ず成功する。
! Set (map ,
P , Desc .[[Value]] ,
false )を実行する。
もしDesc が[[Writable]] フィールドを持ち、Desc .[[Writable]] がfalse なら、
! map .[[Delete]] (P )を実行する。
true を返す。
10.4.4.3 [[Get]] ( P ,
Receiver )
argumentsエキゾチックオブジェクト args の[[Get]] 内部メソッドは、引数P (プロパティキー )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なECMAScript言語値 またはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
map をargs .[[ParameterMap]] とする。
isMapped を! HasOwnProperty (map ,
P )とする。
もしisMapped がfalse なら、
? OrdinaryGet (args ,
P , Receiver )を返す。
それ以外の場合、
保証 :map にはP の仮引数マッピングが含まれている。
! Get (map ,
P )を返す。
10.4.4.4 [[Set]] ( P ,
V , Receiver )
argumentsエキゾチックオブジェクト args の[[Set]] 内部メソッドは、引数P (プロパティキー )、V (ECMAScript言語値 )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしSameValue (args ,
Receiver )がfalse なら、
isMapped をfalse とする。
それ以外の場合、
map をargs .[[ParameterMap]] とする。
isMapped を! HasOwnProperty (map ,
P )とする。
もしisMapped がtrue なら、
保証 :argumentsオブジェクトでマッピングされる仮引数は常に書き込み可能なので、次のSetは必ず成功する。
! Set (map ,
P , V , false )を実行する。
? OrdinarySet (args ,
P , V , Receiver )を返す。
10.4.4.5 [[Delete]] ( P )
argumentsエキゾチックオブジェクト args の[[Delete]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
map をargs .[[ParameterMap]] とする。
isMapped を! HasOwnProperty (map ,
P )とする。
result を? OrdinaryDelete (args ,
P )とする。
もしresult がtrue かつisMapped がtrue なら、
! map .[[Delete]] (P )を実行する。
result を返す。
10.4.4.6 CreateUnmappedArgumentsObject (
argumentsList )
抽象操作CreateUnmappedArgumentsObjectは、引数argumentsList (List (要素はECMAScript言語値 ))を取り、通常オブジェクト を返す。呼び出されたとき、次の手順を実行する:
len をargumentsList の要素数とする。
obj をOrdinaryObjectCreate (%Object.prototype% ,
« [[ParameterMap]] »)とする。
obj .[[ParameterMap]] をundefined に設定する。
! DefinePropertyOrThrow (obj ,
"length" , PropertyDescriptor { [[Value]] : 𝔽 (len ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
index を0とする。
繰り返し、index
< len の間、
val をargumentsList [index ]とする。
! CreateDataPropertyOrThrow (obj ,
! ToString (𝔽 (index )),
val )を実行する。
index をindex + 1に設定する。
! DefinePropertyOrThrow (obj ,
%Symbol.iterator% ,
PropertyDescriptor { [[Value]] : %Array.prototype.values%,
[[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
! DefinePropertyOrThrow (obj ,
"callee" , PropertyDescriptor { [[Get]] :
%ThrowTypeError% , [[Set]] : %ThrowTypeError% ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
obj を返す。
10.4.4.7 CreateMappedArgumentsObject ( func ,
formals , argumentsList , env )
抽象操作CreateMappedArgumentsObjectは、引数func (オブジェクト)、formals (Parse
Node )、argumentsList (List (要素はECMAScript言語値 ))、env (Environment Record )を取り、argumentsエキゾチックオブジェクト を返す。呼び出されたとき、次の手順を実行する:
保証 :formals はrestパラメータ、バインディングパターン、初期化子を含まない。ただし重複識別子は許可される。
len をargumentsList の要素数とする。
obj をMakeBasicObject (« [[Prototype]] , [[Extensible]] , [[ParameterMap]] »)とする。
obj .[[GetOwnProperty]] を10.4.4.1 で規定されるものに設定する。
obj .[[DefineOwnProperty]] を10.4.4.2 で規定されるものに設定する。
obj .[[Get]] を10.4.4.3 で規定されるものに設定する。
obj .[[Set]] を10.4.4.4 で規定されるものに設定する。
obj .[[Delete]] を10.4.4.5 で規定されるものに設定する。
obj .[[Prototype]] を%Object.prototype% に設定する。
map をOrdinaryObjectCreate (null )とする。
obj .[[ParameterMap]] をmap に設定する。
parameterNames をBoundNames of
formals とする。
numberOfParameters をparameterNames の要素数とする。
index を0とする。
繰り返し、index < len の間、
val をargumentsList [index ]とする。
! CreateDataPropertyOrThrow (obj ,
! ToString (𝔽 (index )),
val )を実行する。
index をindex + 1に設定する。
! DefinePropertyOrThrow (obj ,
"length" , PropertyDescriptor { [[Value]] : 𝔽 (len ), [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
mappedNames を新しい空のList とする。
index をnumberOfParameters - 1に設定する。
繰り返し、index ≥ 0の間、
name をparameterNames [index ]とする。
もしmappedNames がname を含まないなら、
name をmappedNames に追加する。
もしindex < len なら、
g をMakeArgGetter (name ,
env )とする。
p をMakeArgSetter (name ,
env )とする。
! map .[[DefineOwnProperty]] (! ToString (𝔽 (index )),
PropertyDescriptor { [[Set]] :
p , [[Get]] :
g , [[Enumerable]] :
false , [[Configurable]] :
true }) を実行する。
index をindex - 1に設定する。
! DefinePropertyOrThrow (obj ,
%Symbol.iterator% ,
PropertyDescriptor { [[Value]] : %Array.prototype.values%,
[[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
! DefinePropertyOrThrow (obj ,
"callee" , PropertyDescriptor { [[Value]] : func , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : true }) を実行する。
obj を返す。
10.4.4.7.1 MakeArgGetter ( name , env )
抽象操作MakeArgGetterは、引数name (文字列)、env (Environment Record )を取り、関数オブジェクト を返す。これは、実行時にenv 内のname に束縛された値を返す組み込み関数オブジェクト を生成する。呼び出されたとき、次の手順を実行する:
getterClosure を新しいAbstract
Closure (パラメータなし、name とenv をキャプチャ)とし、呼び出されたとき次を行う:
NormalCompletion (!
env .GetBindingValue(name ,
false ))を返す。
getter をCreateBuiltinFunction (getterClosure ,
0, "" , « »)とする。
注:getter はECMAScriptコードから直接アクセスされることはない。
getter を返す。
10.4.4.7.2 MakeArgSetter ( name , env )
抽象操作MakeArgSetterは、引数name (文字列)、env (Environment Record )を取り、関数オブジェクト を返す。これは、実行時にenv 内のname に値をセットする組み込み関数オブジェクト を生成する。呼び出されたとき、次の手順を実行する:
setterClosure を新しいAbstract
Closure (パラメータは(value )、name とenv をキャプチャ)とし、呼び出されたとき次を行う:
NormalCompletion (!
env .SetMutableBinding(name , value ,
false ))を返す。
setter をCreateBuiltinFunction (setterClosure ,
1, "" , « »)とする。
注:setter はECMAScriptコードから直接アクセスされることはない。
setter を返す。
10.4.5 TypedArray エキゾチックオブジェクト
TypedArray は、正規数値文字列 であるプロパティキー のうち、範囲内の整数インデックス を用いて同種要素にアクセスし、それ以外はプロトタイプチェーン探索無しで存在しないことを保証するという特殊な扱いを行うエキゾチックオブジェクト である。
注
任意の数値n についてToString (n )が正規数値文字列 となるので、実装は実際に文字列変換を行わずにTypedArrayのプロパティキー として数値を扱ってよい。
TypedArray は通常オブジェクト と同じ内部スロットに加え、[[ViewedArrayBuffer]] 、[[TypedArrayName]] 、[[ContentType]] 、[[ByteLength]] 、[[ByteOffset]] 、[[ArrayLength]] 内部スロットを持つ。
オブジェクトの[[PreventExtensions]] 、[[GetOwnProperty]] 、[[HasProperty]] 、[[DefineOwnProperty]] 、[[Get]] 、[[Set]] 、[[Delete]] 、[[OwnPropertyKeys]] 内部メソッドがこの節の定義を、その他の本質的内部メソッドが10.1 の定義を使う場合、そのオブジェクトは TypedArray である。これらのメソッドはTypedArrayCreate により付与される。
10.4.5.1 [[PreventExtensions]] ( )
TypedArray O の[[PreventExtensions]] 内部メソッドは引数を取らず、normal completion
containing なBooleanを返す。呼び出されたとき、次の手順を実行する:
注:6.1.7.3 で規定される拡張性関連の不変条件により、このメソッドは、O がプロパティを増やしたり(あるいは失ってから再度増やしたり)できる場合(基礎バッファがリサイズされるときの整数インデックス名のプロパティなど)、true を返すことはできない。
もしIsTypedArrayFixedLength (O )がfalse なら、false を返す。
OrdinaryPreventExtensions (O )を返す。
10.4.5.2 [[GetOwnProperty]] (
P )
TypedArray O の[[GetOwnProperty]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なプロパティディスクリプタ またはundefined を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、
value をTypedArrayGetElement (O ,
numericIndex )とする。
もしvalue がundefined なら、undefined を返す。
プロパティディスクリプタ { [[Value]] : value ,
[[Writable]] : true , [[Enumerable]] : true ,
[[Configurable]] : true }
を返す。
OrdinaryGetOwnProperty (O ,
P )を返す。
10.4.5.3 [[HasProperty]] ( P
)
TypedArray O の[[HasProperty]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、IsValidIntegerIndex (O ,
numericIndex )を返す。
? OrdinaryHasProperty (O ,
P )を返す。
10.4.5.4 [[DefineOwnProperty]] (
P , Desc )
TypedArray O の[[DefineOwnProperty]] 内部メソッドは、引数P (プロパティキー )、Desc (プロパティディスクリプタ )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、
もしIsValidIntegerIndex (O ,
numericIndex )がfalse なら、false を返す。
もしDesc が[[Configurable]] フィールドを持ち、かつDesc .[[Configurable]] がfalse なら、false を返す。
もしDesc が[[Enumerable]] フィールドを持ち、かつDesc .[[Enumerable]] がfalse なら、false を返す。
もしIsAccessorDescriptor (Desc )がtrue なら、false を返す。
もしDesc が[[Writable]] フィールドを持ち、かつDesc .[[Writable]] がfalse なら、false を返す。
もしDesc が[[Value]] フィールドを持つなら、?
TypedArraySetElement (O ,
numericIndex , Desc .[[Value]] )を実行する。
true を返す。
! OrdinaryDefineOwnProperty (O ,
P , Desc )を返す。
10.4.5.5 [[Get]] ( P ,
Receiver )
TypedArray O の[[Get]] 内部メソッドは、引数P (プロパティキー )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なECMAScript言語値 またはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、
TypedArrayGetElement (O ,
numericIndex )を返す。
? OrdinaryGet (O , P ,
Receiver )を返す。
10.4.5.6 [[Set]] ( P ,
V , Receiver )
TypedArray O の[[Set]] 内部メソッドは、引数P (プロパティキー )、V (ECMAScript言語値 )、Receiver (ECMAScript言語値 )を取り、normal completion
containing なBooleanまたはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、
もしSameValue (O ,
Receiver )がtrue なら、
? TypedArraySetElement (O ,
numericIndex , V )を実行する。
true を返す。
もしIsValidIntegerIndex (O ,
numericIndex )がfalse なら、true を返す。
? OrdinarySet (O , P ,
V , Receiver )を返す。
10.4.5.7 [[Delete]] ( P )
TypedArray O の[[Delete]] 内部メソッドは、引数P (プロパティキー )を取り、normal completion
containing なBooleanを返す。呼び出されたとき、次の手順を実行する:
もしP が文字列 なら、
numericIndex をCanonicalNumericIndexString (P )とする。
もしnumericIndex がundefined でなければ、
もしIsValidIntegerIndex (O ,
numericIndex )がfalse ならtrue 、そうでなければfalse を返す。
! OrdinaryDelete (O ,
P )を返す。
10.4.5.8 [[OwnPropertyKeys]] ( )
TypedArray O の[[OwnPropertyKeys]] 内部メソッドは引数を取らず、normal completion
containing なList (要素はプロパティキー )を返す。呼び出されたとき、次の手順を実行する:
taRecord をMakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst )とする。
keys を新しい空のList とする。
もしIsTypedArrayOutOfBounds (taRecord )がfalse なら、
length をTypedArrayLength (taRecord )とする。
0 ≤ i < length となる各整数 i について、昇順で:
! ToString (𝔽 (i ))をkeys に追加する。
O の自身のプロパティキー P について、P が文字列 かつP が整数インデックス でないものを生成順に昇順で:
P をkeys に追加する。
O の自身のプロパティキー P について、P がシンボル であるものを生成順に昇順で:
P をkeys に追加する。
keys を返す。
10.4.5.9 バッファ証人レコード付きTypedArray
バッファ証人レコード付きTypedArray は、Record 値であり、TypedArray と、参照しているバッファのキャッシュされたバイト長をカプセル化するためのものである。これは、参照バッファが拡張可能なSharedArrayBuffer の場合に、バイト長データブロックのメモリ読み出しイベントが1回だけ共有されることを保証するために使われる。
バッファ証人レコード付きTypedArrayは、表32 に示すフィールドを持つ。
表32: バッファ証人レコード付きTypedArray
のフィールド
フィールド名
値
意味
[[Object]]
TypedArray
バッファのバイト長がロードされるTypedArray 。
[[CachedBufferByteLength]]
0以上の整数 またはdetached
Record 生成時のオブジェクトの[[ViewedArrayBuffer]] のバイト長。
10.4.5.10 MakeTypedArrayWithBufferWitnessRecord (
obj , order )
抽象操作MakeTypedArrayWithBufferWitnessRecordは、引数obj (TypedArray )、order (seq-cst またはunordered )を取り、バッファ証人レコード付きTypedArray を返す。呼び出されたとき、次の手順を実行する:
buffer をobj .[[ViewedArrayBuffer]] とする。
もしIsDetachedBuffer (buffer )がtrue なら、
byteLength をdetached とする。
それ以外の場合、
byteLength をArrayBufferByteLength (buffer ,
order )とする。
バッファ証人レコード付きTypedArray
{ [[Object]] : obj , [[CachedBufferByteLength]] : byteLength }を返す。
10.4.5.11 TypedArrayCreate ( prototype )
抽象操作TypedArrayCreateは、引数prototype (オブジェクト)を取り、TypedArray を返す。これは新しいTypedArrays の生成を規定する。呼び出されたとき、次の手順を実行する:
internalSlotsList を« [[Prototype]] , [[Extensible]] , [[ViewedArrayBuffer]] , [[TypedArrayName]] , [[ContentType]] , [[ByteLength]] ,
[[ByteOffset]] , [[ArrayLength]]
»とする。
A をMakeBasicObject (internalSlotsList )とする。
A .[[PreventExtensions]] を10.4.5.1 で規定されるものに設定する。
A .[[GetOwnProperty]] を10.4.5.2 で規定されるものに設定する。
A .[[HasProperty]] を10.4.5.3 で規定されるものに設定する。
A .[[DefineOwnProperty]] を10.4.5.4 で規定されるものに設定する。
A .[[Get]] を10.4.5.5 で規定されるものに設定する。
A .[[Set]] を10.4.5.6 で規定されるものに設定する。
A .[[Delete]] を10.4.5.7 で規定されるものに設定する。
A .[[OwnPropertyKeys]] を10.4.5.8 で規定されるものに設定する。
A .[[Prototype]] をprototype に設定する。
A を返す。
10.4.5.12 TypedArrayByteLength ( taRecord )
抽象操作TypedArrayByteLengthは、引数taRecord (バッファ証人レコード付きTypedArray )を取り、0以上の整数 を返す。呼び出されたとき、次の手順を実行する:
もしIsTypedArrayOutOfBounds (taRecord )がtrue なら、0を返す。
length をTypedArrayLength (taRecord )とする。
もしlength = 0 なら、0を返す。
O をtaRecord .[[Object]] とする。
もしO .[[ByteLength]] がauto でないなら、O .[[ByteLength]] を返す。
elementSize をTypedArrayElementSize (O )とする。
length × elementSize を返す。
10.4.5.13 TypedArrayLength ( taRecord )
抽象操作TypedArrayLengthは、引数taRecord (バッファ証人レコード付きTypedArray )を取り、0以上の整数 を返す。呼び出されたとき、次の手順を実行する:
保証 :IsTypedArrayOutOfBounds (taRecord )はfalse である。
O をtaRecord .[[Object]] とする。
もしO .[[ArrayLength]] がauto でないなら、O .[[ArrayLength]] を返す。
保証 :IsFixedLengthArrayBuffer (O .[[ViewedArrayBuffer]] )はfalse である。
byteOffset をO .[[ByteOffset]] とする。
elementSize をTypedArrayElementSize (O )とする。
byteLength をtaRecord .[[CachedBufferByteLength]] とする。
保証 :byteLength はdetached でない。
floor ((byteLength -
byteOffset ) / elementSize )を返す。
10.4.5.14 IsTypedArrayOutOfBounds ( taRecord )
抽象操作IsTypedArrayOutOfBoundsは、引数taRecord (バッファ証人レコード付きTypedArray )を取り、Booleanを返す。これはオブジェクトの数値プロパティが基礎となるバッファの範囲外のインデックスを参照していないかどうかをチェックする。本操作は上流仕様のための便宜的なもの。呼び出されたとき、次の手順を実行する:
O をtaRecord .[[Object]] とする。
bufferByteLength をtaRecord .[[CachedBufferByteLength]] とする。
保証 :IsDetachedBuffer (O .[[ViewedArrayBuffer]] )がtrue となるのはbufferByteLength がdetached のとき、かつそのときだけである。
もしbufferByteLength がdetached なら、true を返す。
byteOffsetStart をO .[[ByteOffset]] とする。
もしO .[[ArrayLength]] がauto なら、
byteOffsetEnd をbufferByteLength とする。
それ以外の場合、
elementSize をTypedArrayElementSize (O )とする。
byteOffsetEnd をbyteOffsetStart + O .[[ArrayLength]] × elementSize とする。
もしbyteOffsetStart > bufferByteLength または
byteOffsetEnd >
bufferByteLength なら、true を返す。
注:長さ0のTypedArray は範囲外とはみなされない。
false を返す。
10.4.5.15 IsTypedArrayFixedLength ( O )
抽象操作IsTypedArrayFixedLengthは、引数O (TypedArray )を取り、Booleanを返す。呼び出されたとき、次の手順を実行する:
もしO .[[ArrayLength]] がauto なら、false を返す。
buffer をO .[[ViewedArrayBuffer]] とする。
もしIsFixedLengthArrayBuffer (buffer )がfalse かつIsSharedArrayBuffer (buffer )がfalse なら、false を返す。
true を返す。
10.4.5.16 IsValidIntegerIndex ( O , index )
抽象操作IsValidIntegerIndexは、引数O (TypedArray )、index (Number)を取り、Booleanを返す。呼び出されたとき、次の手順を実行する:
もしIsDetachedBuffer (O .[[ViewedArrayBuffer]] )がtrue なら、false を返す。
もしindex が整数値(Number) でなければ、false を返す。
もしindex が-0 𝔽 またはindex <
-0 𝔽 なら、false を返す。
taRecord をMakeTypedArrayWithBufferWitnessRecord (O ,
unordered )とする。
注:バッファが拡張可能なSharedArrayBufferの場合、境界チェックは同期化操作ではない。
もしIsTypedArrayOutOfBounds (taRecord )がtrue なら、false を返す。
length をTypedArrayLength (taRecord )とする。
もしℝ (index )
≥ length なら、false を返す。
true を返す。
10.4.5.17 TypedArrayGetElement ( O , index
)
抽象操作TypedArrayGetElementは、引数O (TypedArray )、index (Number)を取り、Number,
BigInt, またはundefined を返す。呼び出されたとき、次の手順を実行する:
もしIsValidIntegerIndex (O ,
index )がfalse なら、undefined を返す。
offset をO .[[ByteOffset]] とする。
elementSize をTypedArrayElementSize (O )とする。
byteIndexInBuffer を(ℝ (index ) × elementSize ) +
offset とする。
elementType をTypedArrayElementType (O )とする。
GetValueFromBuffer (O .[[ViewedArrayBuffer]] , byteIndexInBuffer ,
elementType , true ,
unordered )を返す。
10.4.5.18 TypedArraySetElement ( O , index ,
value )
抽象操作 TypedArraySetElement は、引数 O (TypedArray )、index (Number)、および
value (ECMAScript 言語値 )を取り、unused を含む normal
completion または throw completion
のいずれかを返す。この操作は呼び出されたとき、次の手順を実行する:
もし O .[[ContentType]] が
bigint なら、numValue に ? ToBigInt (value ) を設定する。
それ以外の場合、numValue に ? ToNumber (value ) を設定する。
IsValidIntegerIndex (O ,
index ) が true なら、
offset に O .[[ByteOffset]]
を設定する。
elementSize に TypedArrayElementSize (O )
を設定する。
byteIndexInBuffer に (ℝ (index ) ×
elementSize ) + offset を設定する。
elementType に TypedArrayElementType (O )
を設定する。
SetValueInBuffer (O .[[ViewedArrayBuffer]] , byteIndexInBuffer ,
elementType , numValue , true ,
unordered ) を実行する。
unused を返す。
注
この操作は常に成功したように見えるが、TypedArray の末尾を越えて書き込もうとした場合や、切り離された
ArrayBuffer に支えられている TypedArray に対しては何の効果も持たない。
10.4.5.19 IsArrayBufferViewOutOfBounds ( O )
抽象操作 IsArrayBufferViewOutOfBounds は、引数 O (TypedArray または
DataView)を取り、Boolean を返す。この操作は、TypedArray の数値プロパティや DataView
オブジェクトのメソッドのいずれかが、基礎となるデータブロックの範囲外のインデックスで値を参照できるかどうかを判定する。これは上流仕様の便宜のために存在する抽象操作である。呼び出されたとき、次の手順を実行する:
もし O が [[DataView]] 内部スロットを持つなら、
viewRecord に MakeDataViewWithBufferWitnessRecord (O ,
seq-cst ) を設定する。
IsViewOutOfBounds (viewRecord )
を返す。
taRecord に MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ) を設定する。
IsTypedArrayOutOfBounds (taRecord )
を返す。
10.4.6 モジュール名前空間エキゾチックオブジェクト
モジュール名前空間エキゾチックオブジェクト は、
エキゾチックオブジェクト であり、
ECMAScript の Module
からエクスポートされたバインディングを公開する(16.2.3 を参照)。モジュール名前空間エキゾチックオブジェクト の
String キー付き own プロパティと、Module
によってエクスポートされたバインディング名との間には一対一の対応がある。エクスポートされたバインディングには export *
によって間接的にエクスポートされたバインディングも含まれる。それぞれの String 値の own
プロパティキー は、対応するエクスポートバインディング名の StringValue である。これらが
モジュール名前空間エキゾチックオブジェクト
の唯一の String キー付きプロパティである。それぞれのプロパティは属性 { [[Writable]] :
true , [[Enumerable]] : true , [[Configurable]] : false } を持つ。
モジュール名前空間エキゾチックオブジェクト
は拡張不可能である(not extensible)。
あるオブジェクトが モジュール名前空間エキゾチックオブジェクト であるとは、その [[GetPrototypeOf]] 、[[SetPrototypeOf]] 、[[IsExtensible]] 、[[PreventExtensions]] 、[[GetOwnProperty]] 、[[DefineOwnProperty]] 、[[HasProperty]] 、[[Get]] 、[[Set]] 、[[Delete]] 、[[OwnPropertyKeys]] 内部メソッドが本節の定義を使用し、それ以外の本質的な内部メソッドが
10.1
に定義されるものを使う場合である。これらのメソッドは ModuleNamespaceCreate によって組み込まれる。
モジュール名前空間エキゾチックオブジェクト は、
表 33
で定義される内部スロットを持つ。
表 33: モジュール名前空間エキゾチックオブジェクトの内部スロット
10.4.6.1 [[GetPrototypeOf]] ( )
モジュール名前空間エキゾチックオブジェクト
の [[GetPrototypeOf]] 内部メソッドは引数を取らず、値として
null を含む normal completion を返す。呼び出されたとき、次の手順を実行する:
null を返す。
10.4.6.2 [[SetPrototypeOf]] (
V )
モジュール名前空間エキゾチックオブジェクト
O の [[SetPrototypeOf]] 内部メソッドは引数 V (Object または
null )を取り、値として
Boolean を含む normal completion を返す。呼び出されたとき、次の手順を実行する:
! SetImmutablePrototype (O ,
V ) を返す。
10.4.6.3 [[IsExtensible]] ( )
モジュール名前空間エキゾチックオブジェクト
の [[IsExtensible]] 内部メソッドは引数を取らず、値として
false を含む normal completion を返す。呼び出されたとき、次の手順を実行する:
false を返す。
10.4.6.4 [[PreventExtensions]] ( )
モジュール名前空間エキゾチックオブジェクト
の [[PreventExtensions]] 内部メソッドは引数を取らず、値として
true を含む normal completion を返す。呼び出されたとき、次の手順を実行する:
true を返す。
10.4.6.5 [[GetOwnProperty]] (
P )
モジュール名前空間エキゾチックオブジェクト
O の [[GetOwnProperty]] 内部メソッドは、引数 P (プロパティキー )を取り、normal
completion (Property
Descriptor または undefined を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
もし P が Symbol
である 場合、OrdinaryGetOwnProperty (O ,
P ) を返す。
exports を O .[[Exports]] とする。
もし exports が P を含まない場合、undefined を返す。
value を ? O .[[Get]] (P , O ) とする。
PropertyDescriptor { [[Value]] : value ,
[[Writable]] : true , [[Enumerable]] : true , [[Configurable]] : false } を返す。
10.4.6.6 [[DefineOwnProperty]] (
P , Desc )
モジュール名前空間エキゾチックオブジェクト
O の [[DefineOwnProperty]] 内部メソッドは、引数
P (プロパティキー )および Desc
(Property
Descriptor )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
もし P が Symbol
である 場合、! OrdinaryDefineOwnProperty (O ,
P , Desc ) を返す。
current を ? O .[[GetOwnProperty]] (P ) とする。
もし current が undefined なら、false
を返す。
もし Desc が [[Configurable]] フィールドを持ち、かつ
Desc .[[Configurable]] が
true である場合、false を返す。
もし Desc が [[Enumerable]] フィールドを持ち、かつ
Desc .[[Enumerable]] が false
である場合、false を返す。
もし IsAccessorDescriptor (Desc )
が true なら、false を返す。
もし Desc が [[Writable]] フィールドを持ち、かつ
Desc .[[Writable]] が false
である場合、false を返す。
もし Desc が [[Value]] フィールドを持つなら、SameValue (Desc .[[Value]] , current .[[Value]] ) を返す。
true を返す。
10.4.6.7 [[HasProperty]] ( P
)
モジュール名前空間エキゾチックオブジェクト
O の [[HasProperty]] 内部メソッドは、引数 P (プロパティキー )を取り、値として Boolean を含む
normal completion を返す。呼び出されたとき、次の手順を実行する:
もし P が Symbol
である 場合、! OrdinaryHasProperty (O ,
P ) を返す。
exports を O .[[Exports]] とする。
もし exports が P を含む場合、true を返す。
false を返す。
10.4.6.8 [[Get]] ( P ,
Receiver )
モジュール名前空間エキゾチックオブジェクト
O の [[Get]] 内部メソッドは、引数 P (プロパティキー )および
Receiver (ECMAScript 言語値 )を取り、
normal
completion (ECMAScript
言語値 を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
もし P が Symbol
である 場合、
! OrdinaryGet (O ,
P , Receiver ) を返す。
exports を O .[[Exports]] とする。
もし exports が P を含まない場合、undefined を返す。
m を O .[[Module]] とする。
binding を m .ResolveExport(P ) とする。
アサート :
binding は ResolvedBinding レコード である。
targetModule を binding .[[Module]]
とする。
アサート :
targetModule は undefined ではない。
もし binding .[[BindingName]] が
namespace である場合、
GetModuleNamespace (targetModule )
を返す。
targetEnv を targetModule .[[Environment]] とする。
もし targetEnv が empty
である場合、ReferenceError 例外をスローする。
? targetEnv .GetBindingValue(binding .[[BindingName]] , true ) を返す。
注
ResolveExport は副作用を持たない。この操作が特定の exportName ・resolveSet
の組み合わせで呼ばれるたびに、常に同じ結果を返さなければならない。実装は各 [[Exports]] に対して
ResolveExport の結果を事前計算・キャッシュしてもよい。モジュール名前空間エキゾチックオブジェクト
のために。
10.4.6.9 [[Set]] ( P ,
V , Receiver )
モジュール名前空間エキゾチックオブジェクト
の [[Set]] 内部メソッドは、引数 P (プロパティキー )、V (ECMAScript
言語値 )、Receiver (ECMAScript 言語値 )を取り、値として
false を含む normal completion を返す。呼び出されたとき、次の手順を実行する:
false を返す。
10.4.6.10 [[Delete]] ( P )
モジュール名前空間エキゾチックオブジェクト
O の [[Delete]] 内部メソッドは、引数 P (プロパティキー )を取り、値として Boolean を含む
normal completion を返す。呼び出されたとき、次の手順を実行する:
もし P が Symbol
である 場合、
! OrdinaryDelete (O ,
P ) を返す。
exports を O .[[Exports]] とする。
もし exports が P を含む場合、false を返す。
true を返す。
10.4.6.11 [[OwnPropertyKeys]] ( )
モジュール名前空間エキゾチックオブジェクト
O の [[OwnPropertyKeys]] 内部メソッドは引数を取らず、normal
completion (リスト (プロパティキー )を含む)を返す。呼び出されたとき、次の手順を実行する:
exports を O .[[Exports]] とする。
symbolKeys を OrdinaryOwnPropertyKeys (O )
とする。
リスト連結 により exports と
symbolKeys を結合したリストを返す。
10.4.6.12 ModuleNamespaceCreate ( module ,
exports )
抽象操作 ModuleNamespaceCreate は、引数 module (Module Record )および
exports (String
のリスト )を取り、モジュール名前空間エキゾチックオブジェクト
を返す。これは新しい モジュール名前空間エキゾチックオブジェクト
の生成を指定するために用いられる。呼び出されたとき、次の手順を実行する:
アサート :
module .[[Namespace]] は
empty である。
internalSlotsList を 表
33 に記載されている内部スロットとする。
M を MakeBasicObject (internalSlotsList )
とする。
M の本質的な内部メソッドを 10.4.6
で指定された定義に設定する。
M .[[Module]] に module を設定する。
sortedExports を リスト (要素は
exports の要素を辞書式コードユニット順 にソートしたもの)とする。
M .[[Exports]] に sortedExports を設定する。
M の own プロパティを 28.3
の定義に対応して作成する。
module .[[Namespace]] に M を設定する。
M を返す。
10.4.7 不変プロトタイプエキゾチックオブジェクト
不変プロトタイプエキゾチックオブジェクト は、
エキゾチックオブジェクト であり、初期化後は変更されない [[Prototype]] 内部スロットを持つ。
あるオブジェクトが 不変プロトタイプエキゾチックオブジェクト
であるとは、その [[SetPrototypeOf]] 内部メソッドが以下の実装を用いる場合である(その他の本質的な内部メソッドは、対象の
不変プロトタイプエキゾチックオブジェクト
に応じて任意の実装を用いてよい)。
注
他の エキゾチックオブジェクト とは異なり、不変プロトタイプエキゾチックオブジェクト 専用の生成抽象操作は提供されていない。これは、これらが
%Object.prototype%
や ホスト環境 でのみ使用され、
ホスト環境 では、該当オブジェクトが他の意味でもエキゾチックな場合があり、独自の生成操作が必要となるためである。
10.4.7.1 [[SetPrototypeOf]] (
V )
不変プロトタイプエキゾチックオブジェクト
O の [[SetPrototypeOf]] 内部メソッドは、引数 V (Object
または null )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? SetImmutablePrototype (O ,
V ) を返す。
10.4.7.2 SetImmutablePrototype ( O , V )
抽象操作 SetImmutablePrototype は、引数 O (Object)、V (Object または
null )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
current を ? O .[[GetPrototypeOf]] () とする。
SameValue (V ,
current ) が true なら、true を返す。
false を返す。
10.5 Proxy オブジェクトの内部メソッドおよび内部スロット
Proxy オブジェクトは、エキゾチックオブジェクト であり、その本質的な内部メソッドの一部が ECMAScript
コードによって実装されている。すべての Proxy オブジェクトは [[ProxyHandler]] という内部スロットを持つ。[[ProxyHandler]] の値は、プロキシのハンドラーオブジェクト と呼ばれるオブジェクト、または
null である。ハンドラーオブジェクトのメソッド(表 34 参照)は、1つ以上の Proxy
オブジェクトの内部メソッドの実装を拡張するために利用できる。すべての Proxy オブジェクトは [[ProxyTarget]]
という内部スロットも持ち、その値はオブジェクトまたは null である。このオブジェクトはプロキシのターゲットオブジェクト と呼ばれる。
あるオブジェクトが Proxy
エキゾチックオブジェクト であるとは、その本質的な内部メソッド(該当する場合は [[Call]] および [[Construct]] を含む)が本節の定義を使う場合である。これらの内部メソッドは ProxyCreate で設定される。
表 34: Proxy ハンドラーメソッド
内部メソッド
ハンドラーメソッド
[[GetPrototypeOf]]
getPrototypeOf
[[SetPrototypeOf]]
setPrototypeOf
[[IsExtensible]]
isExtensible
[[PreventExtensions]]
preventExtensions
[[GetOwnProperty]]
getOwnPropertyDescriptor
[[DefineOwnProperty]]
defineProperty
[[HasProperty]]
has
[[Get]]
get
[[Set]]
set
[[Delete]]
deleteProperty
[[OwnPropertyKeys]]
ownKeys
[[Call]]
apply
[[Construct]]
construct
ハンドラーメソッドが Proxy
オブジェクト内部メソッドの実装として呼び出されるとき、そのハンドラーメソッドにはプロキシのターゲットオブジェクトがパラメータとして渡される。プロキシのハンドラーオブジェクトは必ずしもすべての本質的な内部メソッドに対応するメソッドを持つ必要はない。プロキシ上で内部メソッドが呼ばれた際に、ハンドラーオブジェクトが該当するトラップメソッドを持たない場合は、プロキシのターゲットオブジェクト上の対応する内部メソッドが呼び出される。
Proxy オブジェクトの [[ProxyHandler]] および [[ProxyTarget]]
内部スロットは、オブジェクト生成時に常に初期化され、通常は変更されない。一部の Proxy
オブジェクトは、生成後にrevoke(無効化) できるような方法で作成される。プロキシが無効化されると、その [[ProxyHandler]] および [[ProxyTarget]] 内部スロットは
null に設定され、その後その Proxy オブジェクト上の内部メソッドを呼び出すと TypeError
例外がスローされる。
Proxy オブジェクトは本質的な内部メソッドの実装を任意の ECMAScript コードで提供可能であるため、ハンドラーメソッドが 6.1.7.3
で定義される不変条件(invariant)を破る Proxy オブジェクトを定義することも可能である。6.1.7.3
で定義される内部メソッドの不変条件のうち、いくつかは本質的な完全性不変条件である。これらの不変条件は本節で規定される Proxy
オブジェクト内部メソッドによって明示的に強制される。ECMAScript 実装は、あらゆる不変条件違反が発生し得る状況でも堅牢でなければならない。
以下のアルゴリズム記述では、O は ECMAScript Proxy オブジェクト、P は プロパティキー の値、V は任意の ECMAScript 言語値 、Desc は
プロパティディスクリプタ レコードであると仮定する。
10.5.1 [[GetPrototypeOf]] ( )
Proxy
エキゾチックオブジェクト O の [[GetPrototypeOf]]
内部メソッドは引数を取らず、Object または null を含む normal completion または
throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :handler は Object
である 。
trap を ? GetMethod (handler ,
"getPrototypeOf" ) とする。
もし trap が undefined なら、
? target .[[GetPrototypeOf]] () を返す。
handlerProto を ? Call (trap ,
handler , « target » ) とする。
もし handlerProto が Object でない かつ handlerProto が
null でない場合、TypeError 例外をスローする。
extensibleTarget を ? IsExtensible (target ) とする。
もし extensibleTarget が true なら、handlerProto を返す。
targetProto を ? target .[[GetPrototypeOf]] () とする。
もし SameValue (handlerProto ,
targetProto ) が false なら、TypeError
例外をスローする。
handlerProto を返す。
注
Proxy オブジェクトの [[GetPrototypeOf]] は以下の不変条件を強制する:
[[GetPrototypeOf]] の結果は Object または null
でなければならない。
ターゲットオブジェクトが拡張不可能な場合、Proxy オブジェクトに対する [[GetPrototypeOf]]
は、ターゲットオブジェクトに対する [[GetPrototypeOf]] と同じ値を返さなければならない。
10.5.2 [[SetPrototypeOf]] ( V )
Proxy
エキゾチックオブジェクト O の [[SetPrototypeOf]]
内部メソッドは引数 V (Object または null )を取り、Boolean を含む normal completion または
throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :handler は Object
である 。
trap を ? GetMethod (handler ,
"setPrototypeOf" ) とする。
もし trap が undefined なら、
? target .[[SetPrototypeOf]] (V ) を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target , V »)) とする。
もし booleanTrapResult が false なら、false
を返す。
extensibleTarget を ? IsExtensible (target ) とする。
もし extensibleTarget が true なら、true を返す。
targetProto を ? target .[[GetPrototypeOf]] () とする。
もし SameValue (V ,
targetProto ) が false なら、TypeError
例外をスローする。
true を返す。
注
Proxy オブジェクトの [[SetPrototypeOf]] は以下の不変条件を強制する:
[[SetPrototypeOf]] の結果は Boolean
値である。
ターゲットオブジェクトが拡張不可能な場合、引数の値はターゲットオブジェクトに対する [[GetPrototypeOf]] の結果と同じでなければならない。
10.5.3 [[IsExtensible]] ( )
Proxy
エキゾチックオブジェクト O の [[IsExtensible]]
内部メソッドは引数を取らず、Boolean を含む normal
completion または throw
completion を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :handler は Object
である 。
trap を ? GetMethod (handler ,
"isExtensible" ) とする。
もし trap が undefined なら、
? IsExtensible (target ) を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target » )) とする。
targetResult を ? IsExtensible (target ) とする。
もし booleanTrapResult が targetResult
と異なる場合、TypeError 例外をスローする。
booleanTrapResult を返す。
注
Proxy オブジェクトの [[IsExtensible]] は以下の不変条件を強制する:
[[IsExtensible]] の結果は Boolean
値である。
Proxy オブジェクトに対して [[IsExtensible]]
を適用した結果は、同じ引数でターゲットオブジェクトに [[IsExtensible]]
を適用した結果と同じでなければならない。
10.5.4 [[PreventExtensions]] ( )
Proxy
エキゾチックオブジェクト O の [[PreventExtensions]] 内部メソッドは引数を取らず、Boolean を含む normal completion または
throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :handler は Object
である 。
trap を ? GetMethod (handler ,
"preventExtensions" ) とする。
もし trap が undefined なら、
? target .[[PreventExtensions]] () を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target » )) とする。
もし booleanTrapResult が true なら、
extensibleTarget を ? IsExtensible (target ) とする。
もし extensibleTarget が true
なら、TypeError 例外をスローする。
booleanTrapResult を返す。
注
Proxy オブジェクトの [[PreventExtensions]] は以下の不変条件を強制する:
[[PreventExtensions]] の結果は Boolean
値である。
Proxy オブジェクトに対して [[PreventExtensions]] を適用した結果が
true となるのは、ターゲットオブジェクトに対する [[IsExtensible]] の結果が false の場合のみである。
10.5.5 [[GetOwnProperty]] ( P )
Proxy
エキゾチックオブジェクト O の [[GetOwnProperty]]
内部メソッドは、引数 P (プロパティキー )を取り、normal
completion (Property
Descriptor または
undefined を含む)、または throw
completion を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"getOwnPropertyDescriptor" ) とする。
もし trap が undefined なら、
? target .[[GetOwnProperty]] (P ) を返す。
trapResultObj を ? Call (trap ,
handler , « target , P » ) とする。
もし trapResultObj が Object でない かつ
trapResultObj が undefined
でない場合、TypeError 例外をスローする。
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
もし trapResultObj が undefined なら、
もし targetDesc が undefined
なら、undefined を返す。
もし targetDesc .[[Configurable]] が
false なら、TypeError 例外をスローする。
extensibleTarget を ? IsExtensible (target ) とする。
もし extensibleTarget が false
なら、TypeError 例外をスローする。
undefined を返す。
extensibleTarget を ? IsExtensible (target ) とする。
resultDesc を ? ToPropertyDescriptor (trapResultObj )
とする。
CompletePropertyDescriptor (resultDesc )
を実行する。
valid を IsCompatiblePropertyDescriptor (extensibleTarget ,
resultDesc , targetDesc ) とする。
もし valid が false なら、TypeError
例外をスローする。
もし resultDesc .[[Configurable]] が
false なら、
もし targetDesc が undefined または
targetDesc .[[Configurable]] が
true なら、
TypeError 例外をスローする。
もし resultDesc が [[Writable]] フィールドを持ち、かつ
resultDesc .[[Writable]] が
false なら、
アサート : targetDesc は
[[Writable]] フィールドを持つ。
もし targetDesc .[[Writable]] が
true なら、TypeError 例外をスローする。
resultDesc を返す。
注
Proxy オブジェクトの [[GetOwnProperty]] は以下の不変条件を強制する:
[[GetOwnProperty]] の結果は Object または
undefined でなければならない。
ターゲットオブジェクトの non-configurable な own プロパティが存在する場合、そのプロパティは存在しないと報告できない。
ターゲットオブジェクトに own プロパティが存在し、かつターゲットオブジェクトが拡張不可能な場合、そのプロパティは存在しないと報告できない。
ターゲットオブジェクトに own プロパティが存在しない、かつターゲットオブジェクトが拡張不可能な場合、そのプロパティは存在すると報告できない。
non-configurable として報告できるのは、ターゲットオブジェクトの non-configurable な own プロパティが存在する場合のみである。
non-configurable かつ non-writable として報告できるのは、ターゲットオブジェクトに non-configurable かつ
non-writable な own プロパティが存在する場合のみである。
10.5.6 [[DefineOwnProperty]] (
P , Desc )
Proxy
エキゾチックオブジェクト O の [[DefineOwnProperty]] 内部メソッドは、引数 P (プロパティキー )および
Desc (Property
Descriptor )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"defineProperty" ) とする。
もし trap が undefined なら、
? target .[[DefineOwnProperty]] (P ,
Desc ) を返す。
descObj を FromPropertyDescriptor (Desc )
とする。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target , P , descObj »)) とする。
もし booleanTrapResult が false なら、false
を返す。
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
extensibleTarget を ? IsExtensible (target ) とする。
もし Desc が [[Configurable]] フィールドを持ち、かつ
Desc .[[Configurable]] が false なら、
settingConfigFalse を true とする。
それ以外の場合、
settingConfigFalse を false とする。
もし targetDesc が undefined なら、
もし extensibleTarget が false
なら、TypeError 例外をスローする。
もし settingConfigFalse が true
なら、TypeError 例外をスローする。
それ以外の場合、
もし IsCompatiblePropertyDescriptor (extensibleTarget ,
Desc , targetDesc ) が false
なら、TypeError 例外をスローする。
もし settingConfigFalse が true かつ
targetDesc .[[Configurable]] が
true なら、TypeError 例外をスローする。
もし IsDataDescriptor (targetDesc )
が true かつ targetDesc .[[Configurable]] が false かつ
targetDesc .[[Writable]] が
true なら、
もし Desc が [[Writable]] フィールドを持ち、かつ
Desc .[[Writable]] が
false なら、TypeError 例外をスローする。
true を返す。
注
Proxy オブジェクトの [[DefineOwnProperty]] は以下の不変条件を強制する:
[[DefineOwnProperty]] の結果は Boolean
値である。
ターゲットオブジェクトが拡張不可能な場合、プロパティを追加できない。
non-configurable にできるのは、対応する non-configurable なターゲットオブジェクトの own プロパティが存在する場合のみ。
non-configurable かつ non-writable にできるのは、対応する non-configurable かつ non-writable
なターゲットオブジェクトの own プロパティが存在する場合のみ。
プロパティに対応するターゲットオブジェクトのプロパティが存在する場合、そのプロパティディスクリプタをターゲットオブジェクトに [[DefineOwnProperty]] で適用しても例外は発生しない。
10.5.7 [[HasProperty]] ( P )
Proxy
エキゾチックオブジェクト O の [[HasProperty]]
内部メソッドは、引数 P (プロパティキー )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"has" ) とする。
もし trap が undefined なら、
? target .[[HasProperty]] (P ) を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target , P » )) とする。
もし booleanTrapResult が false なら、
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
もし targetDesc が undefined でなければ、
もし targetDesc .[[Configurable]] が
false なら、TypeError
例外をスローする。
extensibleTarget を ? IsExtensible (target )
とする。
もし extensibleTarget が false
なら、TypeError 例外をスローする。
booleanTrapResult を返す。
注
Proxy オブジェクトの [[HasProperty]] は以下の不変条件を強制する:
[[HasProperty]] の結果は Boolean
値である。
ターゲットオブジェクトの non-configurable な own プロパティが存在する場合、そのプロパティは存在しないと報告できない。
ターゲットオブジェクトに own プロパティが存在し、かつターゲットオブジェクトが拡張不可能な場合、そのプロパティは存在しないと報告できない。
10.5.8 [[Get]] ( P ,
Receiver )
Proxy
エキゾチックオブジェクト
O の [[Get]] 内部メソッドは、引数 P (プロパティキー )および
Receiver (ECMAScript 言語値 )を取り、
normal
completion (ECMAScript
言語値 を含む)、または throw
completion を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"get" ) とする。
もし trap が undefined なら、
? target .[[Get]] (P , Receiver )
を返す。
trapResult を ? Call (trap ,
handler , « target , P , Receiver » ) とする。
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
もし targetDesc が undefined でなく、かつ
targetDesc .[[Configurable]] が
false なら、
もし IsDataDescriptor (targetDesc )
が true かつ targetDesc .[[Writable]] が false なら、
もし SameValue (trapResult ,
targetDesc .[[Value]] ) が
false なら、TypeError
例外をスローする。
もし IsAccessorDescriptor (targetDesc )
が true かつ targetDesc .[[Get]] が undefined なら、
もし trapResult が undefined
でない場合、TypeError 例外をスローする。
trapResult を返す。
注
Proxy オブジェクトの [[Get]] は以下の不変条件を強制する:
対応するターゲットオブジェクトのプロパティが non-writable, non-configurable な own データプロパティ
の場合、プロパティの値はターゲットオブジェクトのプロパティの値と同じでなければならない。
対応するターゲットオブジェクトのプロパティが [[Get]] 属性が
undefined である non-configurable な own アクセサプロパティ の場合、プロパティの値は
undefined でなければならない。
10.5.9 [[Set]] ( P ,
V , Receiver )
Proxy
エキゾチックオブジェクト
O の [[Set]] 内部メソッドは、引数 P (プロパティキー )、V (ECMAScript
言語値 )、Receiver (ECMAScript
言語値 )を取り、normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"set" ) とする。
もし trap が undefined なら、
? target .[[Set]] (P , V ,
Receiver ) を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target , P , V , Receiver »)) とする。
もし booleanTrapResult が false なら、false
を返す。
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
もし targetDesc が undefined でなく、
targetDesc .[[Configurable]] が
false なら、
もし IsDataDescriptor (targetDesc )
が true かつ targetDesc .[[Writable]] が false なら、
SameValue (V ,
targetDesc .[[Value]] ) が
false なら、TypeError
例外をスローする。
もし IsAccessorDescriptor (targetDesc )
が true なら、
もし targetDesc .[[Set]] が
undefined なら、TypeError
例外をスローする。
true を返す。
注
Proxy オブジェクトの [[Set]] は次の不変条件を強制する:
[[Set]] の結果は Boolean
値である。
対応するターゲットオブジェクトのプロパティが非書き込み・非設定可能な own データプロパティ
の場合、その値をターゲットオブジェクトの値と異なる値に変更することはできない。
対応するターゲットオブジェクトのプロパティが アクセサプロパティ かつ [[Set]] 属性が undefined
の場合、その値を設定することはできない。
10.5.10 [[Delete]] ( P )
Proxy
エキゾチックオブジェクト
O の [[Delete]] 内部メソッドは、引数 P (プロパティキー )を取り、
normal
completion (Boolean を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"deleteProperty" ) とする。
もし trap が undefined なら、
? target .[[Delete]] (P ) を返す。
booleanTrapResult を ToBoolean (? Call (trap , handler , «
target , P »)) とする。
もし booleanTrapResult が false なら、false
を返す。
targetDesc を ? target .[[GetOwnProperty]] (P ) とする。
もし targetDesc が undefined なら、true を返す。
もし targetDesc .[[Configurable]] が
false なら、TypeError 例外をスローする。
extensibleTarget を ? IsExtensible (target ) とする。
もし extensibleTarget が false
なら、TypeError 例外をスローする。
true を返す。
注
Proxy オブジェクトの [[Delete]] は次の不変条件を強制する:
[[Delete]] の結果は Boolean
値である。
対象プロパティがターゲットオブジェクトの非設定可能 own プロパティである場合、それを削除済みとして報告することはできない。
対象プロパティがターゲットオブジェクトの own プロパティであり、ターゲットオブジェクトが拡張不可能な場合、それを削除済みとして報告することはできない。
10.5.11 [[OwnPropertyKeys]] ( )
Proxy
エキゾチックオブジェクト
O の [[OwnPropertyKeys]] 内部メソッドは引数を取らず、normal
completion (リスト (プロパティキー )を含む)、または
throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"ownKeys" ) とする。
もし trap が undefined なら、
? target .[[OwnPropertyKeys]] () を返す。
trapResultArray を ? Call (trap ,
handler , « target » ) とする。
trapResult を ? CreateListFromArrayLike (trapResultArray ,
property-key ) とする。
もし trapResult に重複する要素が含まれていた場合、TypeError 例外をスローする。
extensibleTarget を ? IsExtensible (target ) とする。
targetKeys を ? target .[[OwnPropertyKeys]] () とする。
アサート :
targetKeys は リスト (プロパティキー )である。
アサート :
targetKeys には重複する要素は含まれていない。
targetConfigurableKeys を新しい空の リスト とする。
targetNonconfigurableKeys を新しい空の リスト とする。
targetKeys の各要素 key について、
desc を ? target .[[GetOwnProperty]] (key ) とする。
もし desc が undefined でなく、desc .[[Configurable]] が false なら、
key を targetNonconfigurableKeys に追加する。
それ以外の場合、
key を targetConfigurableKeys に追加する。
もし extensibleTarget が true かつ
targetNonconfigurableKeys が空であるなら、
trapResult を返す。
uncheckedResultKeys を リスト (要素は
trapResult の要素)とする。
targetNonconfigurableKeys の各要素 key について、
もし uncheckedResultKeys に key
が含まれなければ、TypeError 例外をスローする。
key を uncheckedResultKeys から削除する。
もし extensibleTarget が true なら、trapResult を返す。
targetConfigurableKeys の各要素 key について、
もし uncheckedResultKeys に key
が含まれなければ、TypeError 例外をスローする。
key を uncheckedResultKeys から削除する。
もし uncheckedResultKeys が空でない場合、TypeError 例外をスローする。
trapResult を返す。
注
Proxy オブジェクトの [[OwnPropertyKeys]] は次の不変条件を強制する:
[[OwnPropertyKeys]] の結果は リスト である。
返される リスト
には重複する要素が含まれていない。
返される リスト の各要素は
プロパティキー である。
結果の リスト
にはターゲットオブジェクトのすべての非設定可能な own プロパティのキーが含まれていなければならない。
ターゲットオブジェクトが拡張不可能な場合、結果の リスト
にはターゲットオブジェクトのすべての own プロパティのキーが含まれ、それ以外の値を含んではならない。
10.5.12 [[Call]] ( thisArgument ,
argumentsList )
Proxy
エキゾチックオブジェクト
O の [[Call]] 内部メソッドは、引数 thisArgument (ECMAScript 言語値 )および
argumentsList (リスト (ECMAScript 言語値 ))を取り、
normal
completion (ECMAScript
言語値 を含む)、または throw
completion を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"apply" ) とする。
もし trap が undefined なら、
? Call (target ,
thisArgument , argumentsList ) を返す。
argArray を CreateArrayFromList (argumentsList )
とする。
? Call (trap , handler , «
target , thisArgument , argArray » ) を返す。
注
Proxy
エキゾチックオブジェクト は、その [[ProxyTarget]]
内部スロットの初期値が [[Call]] 内部メソッドを持つオブジェクトである場合のみ [[Call]] 内部メソッドを持つ。
10.5.13 [[Construct]] (
argumentsList , newTarget )
Proxy
エキゾチックオブジェクト
O の [[Construct]] 内部メソッドは、引数
argumentsList (リスト (ECMAScript
言語値 ))、newTarget (コンストラクタ )を取り、normal completion (Object
を含む)、または throw completion
を返す。呼び出されたとき、次の手順を実行する:
? ValidateNonRevokedProxy (O )
を実行する。
target を O .[[ProxyTarget]] とする。
アサート :
IsConstructor (target ) は
true である。
handler を O .[[ProxyHandler]] とする。
アサート :
handler は Object である 。
trap を ? GetMethod (handler ,
"construct" ) とする。
もし trap が undefined なら、
? Construct (target ,
argumentsList , newTarget ) を返す。
argArray を CreateArrayFromList (argumentsList )
とする。
newObj を ? Call (trap , handler , «
target , argArray , newTarget » ) とする。
もし newObj が Object でない 場合、TypeError
例外をスローする。
newObj を返す。
注 1
Proxy
エキゾチックオブジェクト は、その [[ProxyTarget]]
内部スロットの初期値が [[Construct]] 内部メソッドを持つオブジェクトである場合のみ [[Construct]] 内部メソッドを持つ。
注 2
Proxy オブジェクトの [[Construct]] は次の不変条件を強制する:
[[Construct]] の結果は Object でなければならない。
10.5.14 ValidateNonRevokedProxy ( proxy )
抽象操作 ValidateNonRevokedProxy は、引数 proxy (Proxy
エキゾチックオブジェクト )を取り、unused を含む normal
completion または throw
completion を返す。proxy が revoke されている場合は
TypeError 例外をスローする。呼び出されたとき、次の手順を実行する:
もし proxy .[[ProxyTarget]] が null
なら、TypeError 例外をスローする。
アサート :
proxy .[[ProxyHandler]] は null
ではない。
unused を返す。
10.5.15 ProxyCreate ( target , handler )
抽象操作 ProxyCreate は、引数 target (ECMAScript
言語値 )、handler (ECMAScript
言語値 )を取り、Proxy エキゾチックオブジェクトを含む
normal completion または throw completion を返す。新しい
Proxy オブジェクトの生成を指定するために使われる。呼び出されたとき、次の手順を実行する:
もし target が Object でない 場合、TypeError
例外をスローする。
もし handler が Object でない 場合、TypeError
例外をスローする。
P を MakeBasicObject (« [[ProxyHandler]] , [[ProxyTarget]] ») とする。
P の本質的な内部メソッド([[Call]] および [[Construct]] を除く)を、10.5
で指定された定義に設定する。
もし IsCallable (target ) が
true なら、
P .[[Call]] を 10.5.12
で指定されたとおりに設定する。
もし IsConstructor (target )
が true なら、
P .[[Construct]] を 10.5.13
で指定されたとおりに設定する。
P .[[ProxyTarget]] に target を設定する。
P .[[ProxyHandler]] に handler を設定する。
P を返す。
11 ECMAScript 言語:ソーステキスト
11.1 ソーステキスト
構文
SourceCharacter ::
任意の Unicode コードポイント
ECMAScript ソーステキスト は、Unicode コードポイントの列である。U+0000 から U+10FFFF までのすべての Unicode
コードポイント値(サロゲートコードポイントを含む)は、ECMAScript 文法で許可される場所で ECMAScript ソーステキスト内に出現できる。ECMAScript
ソーステキストを保存・交換する際に用いられる実際のエンコーディングは本仕様に関係しない。外部ソーステキストのエンコーディングに関わらず、適合 ECMAScript 実装は、ソーステキストを等価な
SourceCharacter 値の列として処理し、それぞれの
SourceCharacter は Unicode
コードポイントである。適合 ECMAScript 実装はソーステキストの正規化を行う必要はなく、正規化を行っているかのように振る舞う必要もない。
結合文字列の構成要素は、ユーザーが全体を 1 文字と考える場合でも、個々の Unicode コードポイントとして扱われる。
注
文字列リテラル、正規表現リテラル、テンプレートリテラル、識別子では、任意の Unicode コードポイントも、その数値値を明示的に表す Unicode
エスケープシーケンスで表すことができる。コメント内では、このようなエスケープシーケンスはコメントの一部として事実上無視される。
ECMAScript は、Unicode エスケープシーケンスの振る舞いが Java プログラミング言語と異なる。たとえば Java プログラム内で
\u000A のようなエスケープシーケンスが単一行コメント内に現れると、それは行終端子(Unicode コードポイント U+000A:LINE FEED
(LF))として解釈され、次のコードポイントはコメントの一部とならない。同様に、Java プログラムの文字列リテラル内で \u000A
が現れると、それも行終端子と解釈され、文字列リテラル内に行終端子を含めることはできない。LINE FEED (LF) を文字列リテラルの値の一部にしたい場合は
\n を使う必要がある。ECMAScript プログラムでは、コメント内の Unicode
エスケープシーケンスは決して解釈されず、コメントの終了に寄与することはない。同様に、ECMAScript プログラム内の文字列リテラル内で発生する Unicode
エスケープシーケンスは常にリテラルの一部となり、行終端子や文字列リテラルの終了となるコードポイントとして解釈されることはない。
11.1.1 静的セマンティクス: UTF16EncodeCodePoint ( cp )
抽象操作 UTF16EncodeCodePoint は、引数 cp (Unicode コードポイント)を取り、文字列を返す。呼び出されたとき、次の手順を実行する:
アサート : 0 ≤
cp ≤ 0x10FFFF.
もし cp ≤ 0xFFFF なら、数値値が cp であるコードユニットからなる文字列値を返す。
cu1 を、数値値が floor ((cp - 0x10000) /
0x400) + 0xD800 であるコードユニットとする。
cu2 を、数値値が ((cp - 0x10000)
modulo
0x400) + 0xDC00 であるコードユニットとする。
cu1 と cu2 の 文字列連結 を返す。
11.1.2 静的セマンティクス: CodePointsToString ( text )
抽象操作 CodePointsToString は、引数 text (Unicode コードポイント列)を取り、文字列を返す。text を
6.1.4
で記述されるように、文字列値に変換する。呼び出されたとき、次の手順を実行する:
result を空文字列とする。
text の各コードポイント cp について、
result を result と UTF16EncodeCodePoint (cp )
の 文字列連結 に設定する。
result を返す。
11.1.3 静的セマンティクス: UTF16SurrogatePairToCodePoint (
lead , trail )
抽象操作 UTF16SurrogatePairToCodePoint は、引数
lead (コードユニット)、trail (コードユニット)を取り、コードポイントを返す。UTF-16 サロゲートペア を成す 2
つのコードユニットをコードポイントに変換する。呼び出されたとき、次の手順を実行する:
アサート :
lead は リーディングサロゲート であり、trail
は トレーリングサロゲート である。
cp を (lead - 0xD800) × 0x400 + (trail - 0xDC00) +
0x10000 とする。
コードポイント cp を返す。
11.1.4 静的セマンティクス: CodePointAt ( string ,
position )
抽象操作 CodePointAt は、引数 string (文字列)、position (非負の 整数 )を取り、Record ([[CodePoint]] (コードポイント)、[[CodeUnitCount]] (正の
整数 )、[[IsUnpairedSurrogate]] (Boolean)フィールドを持つ)を返す。string を
6.1.4 で記述されるように UTF-16
エンコードされたコードポイント列として解釈し、position 番目のコードユニットから始まる 1 つのコードポイントを読み取る。呼び出されたとき、次の手順を実行する:
size を string の長さとする。
アサート :
position ≥ 0 かつ position < size 。
first を string の position 番目のコードユニットとする。
cp を first の数値値を持つコードポイントとする。
もし first が リーディングサロゲート でもトレーリングサロゲート でもない場合、
Record {
[[CodePoint]] : cp , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] :
false } を返す。
もし first が トレーリングサロゲート であるか、position +
1 = size なら、
Record {
[[CodePoint]] : cp , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] : true }
を返す。
second を string の position + 1 番目のコードユニットとする。
もし second が トレーリングサロゲート でない場合、
Record {
[[CodePoint]] : cp , [[CodeUnitCount]] : 1, [[IsUnpairedSurrogate]] : true }
を返す。
cp を UTF16SurrogatePairToCodePoint (first ,
second ) に設定する。
Record { [[CodePoint]] : cp , [[CodeUnitCount]] : 2, [[IsUnpairedSurrogate]] : false } を返す。
11.1.5 静的セマンティクス: StringToCodePoints ( string )
抽象操作 StringToCodePoints は、引数 string (文字列)を取り、コードポイントのリスト を返す。string
を 6.1.4 で記述されるように UTF-16
エンコードされた Unicode テキストとして解釈し、そこから得られる Unicode コードポイント列を返す。呼び出されたとき、次の手順を実行する:
codePoints を新しい空の リスト とする。
size を string の長さとする。
position を 0 とする。
position < size の間、繰り返す:
cp を CodePointAt (string ,
position ) に設定する。
cp .[[CodePoint]] を codePoints
に追加する。
position を position + cp .[[CodeUnitCount]] に設定する。
codePoints を返す。
11.1.6 静的セマンティクス: ParseText ( sourceText ,
goalSymbol )
抽象操作 ParseText は、引数 sourceText (文字列または Unicode
コードポイント列)、goalSymbol (ECMAScript 文法の非終端記号)を取り、Parse Node または非空の SyntaxError オブジェクトのリスト
を返す。呼び出されたとき、次の手順を実行する:
もし sourceText が 文字列
なら、sourceText を StringToCodePoints (sourceText )
に設定する。
sourceText を goalSymbol を ゴール記号 として用いて構文解析し、パース結果について
early
error 条件を解析する。構文解析および early error 検出は、実装定義 の方法でインタリーブされてもよい。
構文解析が成功し、early
errors が見つからなかった場合、パースツリーのルートである Parse
Node (goalSymbol のインスタンス)を返す。
それ以外の場合、解析エラーおよび/または early errors を表す 1 つ以上の SyntaxError
オブジェクトのリスト を返す。複数の解析エラーまたは early error
がある場合、そのリスト内のエラーオブジェクトの数や順序は 実装定義 だが、少なくとも 1 つは存在しなければならない。
注 1
あるテキストに特定の場所で early
error があり、その後に構文エラーがある場合を考える。構文解析の後に early
errors のパスを行う実装は構文エラーのみを報告し、その後 early errors のパスには進まないかもしれない。2
つの処理をインタリーブする実装は early error のみを報告し、構文エラーには進まないかもしれない。3
つ目の実装は両方を報告するかもしれない。いずれも適合している。
注 2
11.2 ソースコードの種類
ECMAScript コードには4つの種類がある:
注 1
関数コードは通常、関数定義(15.2 )、アロー関数定義(15.3 )、メソッド定義(15.4 )、ジェネレーター関数定義(15.5 )、非同期関数定義(15.8 )、非同期ジェネレーター関数定義(15.6 )、および非同期アロー関数(15.9 )の本体として提供される。また、関数
constructor (20.2.1.1 )、GeneratorFunction
constructor (27.3.1.1 )、AsyncFunction constructor (27.7.1.1 )、および
AsyncGeneratorFunction constructor (27.4.1.1 )の引数からも関数コードが生成される。
注 2
関数コードに BindingIdentifier を含める実際的な効果は、strict mode
code の Early Errors が、「use strict」ディレクティブを本体に含む関数の名前となっている BindingIdentifier
にも適用されることである。これは、周囲のコードが strict mode code でなくても同様である。
11.2.1 ディレクティブプロローグと use strict ディレクティブ
ディレクティブプロローグ とは、ExpressionStatement が StatementListItem または ModuleItem の先頭部分として出現し、かつそのシーケンス内の各
ExpressionStatement が
StringLiteral
トークンのみとセミコロンからなる最長の列である。セミコロンは明示的でもよいし、自動セミコロン挿入(12.10 )によって挿入されてもよい。ディレクティブプロローグ は空列でもよい。
use strict
ディレクティブ とは、ディレクティブプロローグ 中の ExpressionStatement であって、その StringLiteral が正確に
"use strict" または 'use strict' というコードポイント列であるものである。use strict
ディレクティブ には EscapeSequence や LineContinuation を含めてはならない。
ディレクティブプロローグ には複数の use strict
ディレクティブ を含めてもよい。ただし、これが発生した場合、実装が警告を出すことがある。
注
ディレクティブプロローグ の ExpressionStatement
は、包含している生成規則の評価時に通常通り評価される。ディレクティブプロローグ 内にあり、かつ use
strict ディレクティブ でなく、実装によって意味が定義されていない ExpressionStatement
に遭遇した場合、通知メカニズムがあれば実装は警告を出すべきである。
11.2.2 厳格モードコード
ECMAScript の構文単位は、無制限モードまたは厳格モードの構文と意味(4.3.2 )で処理されることがある。次の場合、そのコードは
厳格モードコード として解釈される:
厳格モードコードでない ECMAScript コードは、非厳格コード と呼ばれる。
11.2.2.1 静的セマンティクス: IsStrict ( node )
抽象操作 IsStrict は、引数 node (構文ノード )を取り、Boolean
を返す。呼び出されたとき、次の手順を実行する:
もし node
にマッチしたソーステキスト が 厳格モードコード であれば
true を返し、そうでなければ false を返す。
11.2.3 非ECMAScript関数
ECMAScript の実装は、評価動作が ECMAScript ソーステキスト 以外の ホスト定義
の実行可能コードで表現される エキゾチックオブジェクト の関数を評価することをサポートしてもよい。関数オブジェクト が
ECMAScript コード内で定義されたか、組み込み関数であるかは、そのような 関数オブジェクト を呼び出したり呼び出されたりする ECMAScript
コードの視点からは観測できない。
12 ECMAScript言語:字句文法
ECMAScriptのScript または
Module のソーステキストは、最初に入力要素の列、すなわちトークン、行終端子、コメント、または空白へと変換されます。ソーステキストは左から右へと走査され、可能な限り最長のコードポイントの並びを次の入力要素として繰り返し取得します。
字句入力要素の識別は、それを消費する構文文法コンテキストによって影響を受ける場合があります。これには、字句文法に対して複数のゴール記号 が必要となります。InputElementHashbangOrRegExp ゴールは、Script またはModule の先頭で使用されます。InputElementRegExpOrTemplateTail ゴールは、構文文法コンテキストでRegularExpressionLiteral 、TemplateMiddle 、またはTemplateTail が許可される場合に使用されます。InputElementRegExp ゴール記号 は、RegularExpressionLiteral が許可されるが、TemplateMiddle やTemplateTail が許可されないすべての構文文法コンテキストで使用されます。InputElementTemplateTail ゴールは、TemplateMiddle またはTemplateTail が許可され、かつRegularExpressionLiteral が許可されないすべての構文文法コンテキストで使用されます。それ以外のすべてのコンテキストでは、InputElementDiv が字句ゴール記号 として使用されます。
注
複数の字句ゴールを用いることで、自動セミコロン挿入に影響する字句の曖昧さが生じないことが保証されます。例えば、先頭に除算または除算代入、および先頭にRegularExpressionLiteral が両方許可される構文文法コンテキストはありません。これはセミコロン挿入(12.10 参照)によっても影響されません。例えば次のような例の場合:
a = b
/hi/g.exec (c).map (d);
LineTerminator の後、最初の空白でもコメントでもないコードポイントがU+002F(SOLIDUS)であり、構文コンテキストが除算または除算代入を許可する場合、LineTerminator でセミコロンは挿入されません。つまり、上記の例は次のように解釈されます:
a = b / hi / g.exec (c).map (d);
構文
InputElementDiv ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
RightBracePunctuator
InputElementRegExp ::
WhiteSpace
LineTerminator
Comment
CommonToken
RightBracePunctuator
RegularExpressionLiteral
InputElementRegExpOrTemplateTail
::
WhiteSpace
LineTerminator
Comment
CommonToken
RegularExpressionLiteral
TemplateSubstitutionTail
InputElementTemplateTail
::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
TemplateSubstitutionTail
InputElementHashbangOrRegExp
::
WhiteSpace
LineTerminator
Comment
CommonToken
HashbangComment
RegularExpressionLiteral
12.1 Unicode書式制御文字
Unicode書式制御文字(つまりUnicode Character Databaseの「Cf」カテゴリに属する文字、例えばLEFT-TO-RIGHT MARKやRIGHT-TO-LEFT
MARKなど)は、より高次のプロトコル(マークアップ言語など)が存在しない場合に、テキスト範囲の書式を制御するために使用される制御コードです。
編集や表示を容易にするために、ソーステキスト内で書式制御文字を許可することは有用です。すべての書式制御文字は、コメント内、文字列リテラル、テンプレートリテラル、正規表現リテラル内で使用できます。
U+FEFF(ZERO WIDTH NO-BREAK
SPACE)は、主にテキストの先頭でUnicodeであることやテキストの符号化・バイト順序を識別するために使われる書式制御文字です。この目的で意図された<ZWNBSP>文字は、ファイルの連結などの結果としてテキストの先頭以外にも現れることがあります。ECMAScriptソーステキスト では、<ZWNBSP>コードポイントは、コメント、文字列リテラル、テンプレートリテラル、正規表現リテラル外では空白文字として扱われます(12.2 を参照)。
12.2 空白
空白コードポイントは、ソーステキストの可読性を高めたり、トークン(不可分な字句単位)同士を区切るために使われますが、それ以外では意味を持ちません。空白コードポイントは、任意の2つのトークンの間や入力の先頭・末尾に出現できます。空白コードポイントは、StringLiteral 、RegularExpressionLiteral 、Template 、TemplateSubstitutionTail 内に現れる場合、それらはリテラル値の一部として有効なコードポイントと見なされます。また、Comment 内にも現れますが、他の種類のトークンの中には現れません。
ECMAScriptでの空白コードポイントは、表35 に示されています。
表35: 空白コードポイント
コードポイント
名称
略号
U+0009
CHARACTER TABULATION
<TAB>
U+000B
LINE TABULATION
<VT>
U+000C
FORM FEED (FF)
<FF>
U+FEFF
ZERO WIDTH NO-BREAK SPACE
<ZWNBSP>
一般カテゴリ「Space_Separator」に属する任意のコードポイント
<USP>
注1
U+0020(SPACE)およびU+00A0(NO-BREAK SPACE)は<USP>に含まれます。
注2
表35 に記載されたコードポイント以外については、ECMAScriptのWhiteSpace は、Unicodeの「White_Space」プロパティを持っていても一般カテゴリ「Space_Separator」(Zs)に分類されないコードポイントは意図的に除外しています。
構文
WhiteSpace ::
<TAB>
<VT>
<FF>
<ZWNBSP>
<USP>
12.3 行終端子
空白コードポイントと同様に、行終端子コードポイントもソーステキストの可読性を高めたり、トークン(不可分な字句単位)同士を区切るために使われます。ただし空白コードポイントと異なり、行終端子は構文文法の挙動に影響を与える場合があります。一般には、行終端子は任意の2つのトークンの間に現れることができますが、構文文法によって禁止されている箇所もあります。また、行終端子は自動セミコロン挿入の処理(12.10 )にも影響を及ぼします。行終端子は、StringLiteral 、Template 、TemplateSubstitutionTail 以外のトークンの中には出現できません。<LF>と<CR>の行終端子は、StringLiteral トークン内では、LineContinuation の一部としてのみ出現できます。
行終端子はMultiLineComment 内には出現できますが、SingleLineComment 内には出現できません。
行終端子は、正規表現の\sクラスでマッチする空白コードポイントの集合に含まれます。
ECMAScriptでの行終端子コードポイントは、表36 に示されています。
表36: 行終端子コードポイント
コードポイント
Unicode名称
略号
U+000A
LINE FEED (LF)
<LF>
U+000D
CARRIAGE RETURN (CR)
<CR>
U+2028
LINE SEPARATOR
<LS>
U+2029
PARAGRAPH SEPARATOR
<PS>
表36 にあるUnicodeコードポイントのみが行終端子として扱われます。他の改行や改行区切りのUnicodeコードポイントは行終端子とはみなされませんが、表35 に記載された要件を満たす場合は空白として扱われます。<CR><LF>の並びは、行終端子として一般的に使用されます。これは行番号を報告する目的では1つのSourceCharacter と見なされるべきです。
構文
LineTerminator ::
<LF>
<CR>
<LS>
<PS>
LineTerminatorSequence
::
<LF>
<CR>
[lookahead ≠ <LF> ]
<LS>
<PS>
<CR>
<LF>
12.5 ハッシュバンコメント
ハッシュバンコメントは位置依存であり、他の種類のコメントと同様に、構文文法の入力要素ストリームから破棄されます。
構文
12.6 トークン
構文
CommonToken ::
IdentifierName
PrivateIdentifier
Punctuator
NumericLiteral
StringLiteral
Template
注
12.7 名前とキーワード
IdentifierName とReservedWord は、Unicode Standard Annex
#31「Identifier and Pattern Syntax」に記載されたデフォルトの識別子構文にいくつかの小さな修正を加えたものに従って解釈されるトークンです。ReservedWord はIdentifierName の列挙された部分集合です。構文文法は、Identifier をIdentifierName かつReservedWord でないものと定義します。Unicode識別子文法は、Unicode標準で指定された文字プロパティに基づいています。Unicode標準の最新バージョンで指定されたカテゴリ内のUnicodeコードポイントは、すべての準拠するECMAScript実装によってそのカテゴリとして扱われなければなりません。ECMAScript実装は、Unicode標準の後の版で定義された識別子コードポイントを認識しても構いません。
注1
この標準は、特定のコードポイントの追加を指定しています:U+0024(DOLLAR SIGN)およびU+005F(LOW LINE)は、IdentifierName のどこにでも許可されます。
構文
PrivateIdentifier ::
#
IdentifierName
IdentifierName ::
IdentifierStart
IdentifierName
IdentifierPart
IdentifierStart ::
IdentifierStartChar
\
UnicodeEscapeSequence
IdentifierPart ::
IdentifierPartChar
\
UnicodeEscapeSequence
IdentifierStartChar
::
UnicodeIDStart
$
_
IdentifierPartChar ::
UnicodeIDContinue
$
AsciiLetter ::
one of a b c
d e f g h
i j k l m
n o p q r
s t u v w
x y z A B
C D E F G
H I J K L
M N O P Q
R S T U V
W X Y Z
UnicodeIDStart ::
Unicodeプロパティ「ID_Start」を持つ任意のUnicodeコードポイント
UnicodeIDContinue ::
Unicodeプロパティ「ID_Continue」を持つ任意のUnicodeコードポイント
非終端記号UnicodeEscapeSequence の定義は12.9.4 に記載されています。
注2
注3
Unicodeプロパティ「ID_Start」および「ID_Continue」を持つコードポイントの集合には、それぞれ「Other_ID_Start」および「Other_ID_Continue」を持つコードポイントも含まれます。
12.7.1 識別子名
Unicodeエスケープシーケンスは、IdentifierName 内で許可されており、これはIdentifierCodePoint が示すUnicodeEscapeSequence のUnicodeコードポイント1つに相当します。UnicodeEscapeSequence の前にある\は、いかなるコードポイントにも寄与しません。UnicodeEscapeSequence を使用して、それ以外は無効なIdentifierName にコードポイントを追加することはできません。言い換えれば、\UnicodeEscapeSequence を、それが寄与するSourceCharacter に置き換えても、依然として有効なIdentifierName であり、元のIdentifierName とまったく同じ順序のSourceCharacter 要素列でなければなりません。本仕様内でのIdentifierName のすべての解釈は、エスケープシーケンスを用いたかどうかにかかわらず、実際のコードポイントに基づきます。
Unicode標準により正規等価と見なされる2つのIdentifierName は、それぞれのUnicodeEscapeSequence を置き換えた後、まったく同じコードポイント列で表されていない限り、等しいとは見なされません 。
12.7.1.1 静的セマンティクス: 早期エラー
IdentifierStart
::
\
UnicodeEscapeSequence
IdentifierPart ::
\
UnicodeEscapeSequence
12.7.1.2 静的セマンティクス: IdentifierCodePoints
構文指示操作 IdentifierCodePointsは引数を取らず、コードポイントのリスト を返します。次の生成規則に対して分割定義されます:
IdentifierName ::
IdentifierStart
cp を、IdentifierCodePoint (IdentifierStart のもの)とする。
« cp »を返す。
IdentifierName ::
IdentifierName
IdentifierPart
cps を、派生したIdentifierName のIdentifierCodePoints とする。
cp を、IdentifierPart のIdentifierCodePoint とする。
cps と« cp »のリスト結合 を返す。
12.7.1.3 静的セマンティクス: IdentifierCodePoint
構文指示操作 IdentifierCodePointは引数を取らず、コードポイントを返します。次の生成規則に対して分割定義されます:
IdentifierStart
:: IdentifierStartChar
IdentifierStartChar にマッチしたコードポイントを返す。
IdentifierPart ::
IdentifierPartChar
IdentifierPartChar にマッチしたコードポイントを返す。
UnicodeEscapeSequence
::
u
Hex4Digits
Hex4Digits のMV(数値値)を持つコードポイントを返す。
UnicodeEscapeSequence
::
u{
CodePoint
}
CodePoint のMV(数値値)を持つコードポイントを返す。
12.7.2 キーワードと予約語
キーワード とは、IdentifierName にマッチし、かつ構文上の用途を持つトークンです。つまり、いくつかの構文生成規則でリテラル(fixed widthフォント)として現れます。ECMAScriptのキーワードにはif、while、async、awaitなど多数があります。
予約語 とは、識別子として使用できないIdentifierName です。多くのキーワードが予約語ですが、そうでないものもあり、また特定の文脈でのみ予約されているものもあります。ifやwhileは予約語です。awaitはasync関数やモジュール内でのみ予約されます。asyncは予約語ではなく、変数名やラベルとして制限なく使用できます。
この仕様は、どの名前が有効な識別子であり、どれが予約語であるかを指定するために、文法生成規則と早期エラー 規則の組み合わせを使用します。以下のReservedWord リストのすべてのトークンは、awaitとyieldを除き、無条件で予約されます。awaitとyieldの例外は、パラメータ化された構文生成規則を用いて13.1 で指定されます。最後に、いくつかの早期エラー 規則が有効な識別子の集合を制限します。13.1.1 、14.3.1.1 、14.7.5.1 、および15.7.1 を参照してください。まとめると、識別子名には次の5つのカテゴリがあります:
常に識別子として許可され、かつキーワードでないもの(例:Math、window、toString、_など)
決して識別子として許可されないもの、すなわちawaitとyieldを除く下記のReservedWord たち
文脈によって識別子として許可されるもの、すなわちawaitとyield
strict mode
code において文脈によって識別子として許可されないもの:let、static、implements、interface、package、private、protected、public
常に識別子として許可されるが、特定の構文生成規則内ではキーワードとして現れるもの(Identifier が許可されない箇所):as、async、from、get、meta、of、set、target
条件付きキーワード または文脈キーワード という用語は、最後の3つのカテゴリに該当するキーワードを指し、それゆえ、ある文脈では識別子として、別の文脈ではキーワードとして使われることができます。
構文
ReservedWord ::
one of await break
case catch class const
continue debugger default
delete do else enum
export extends false finally
for function if import
in instanceof new null
return super switch this
throw true try typeof
var void while with
yield
注1
5.1.5 に従い、文法中のキーワードは特定のSourceCharacter のリテラル列にマッチします。キーワード中のコードポイントは、\UnicodeEscapeSequence で表現することはできません。
IdentifierName は\UnicodeEscapeSequence を含むことができますが、els\u{65}のようにスペルして"else"という変数を宣言することはできません。早期エラー 規則(13.1.1 )は、予約語と同じStringValue を持つ識別子を排除します。
注2
enumは現時点ではこの仕様でキーワードとして使われていません。これは将来の予約語 であり、将来の言語拡張でキーワードとして使われるために確保されています。
同様に、implements、interface、package、private、protected、publicは、strict
mode code で将来の予約語です。
注3
argumentsとevalはキーワードではありませんが、strict
mode code ではいくつかの制限が課されます。13.1.1 、8.6.4 、15.2.1 、15.5.1 、15.6.1 、および15.8.1 を参照してください。
12.8 区切り記号
構文
Punctuator ::
OptionalChainingPunctuator
OtherPunctuator
OptionalChainingPunctuator
::
?.
[lookahead ∉ DecimalDigit ]
OtherPunctuator ::
いずれか一つ { ( )
[ ] . ... ;
, < > <=
>= == != ===
!== + - * %
** ++ -- <<
>> >>> & |
^ ! ~ &&
|| ?? ? : =
+= -= *= %= **=
<<= >>= >>>=
&= |= ^= &&=
||= ??= =>
DivPunctuator ::
/
/=
RightBracePunctuator
::
}
12.9 リテラル
12.9.1 Nullリテラル
構文
NullLiteral ::
null
12.9.2 真偽値リテラル
構文
BooleanLiteral ::
true
false
12.9.3 数値リテラル
構文
NumericLiteralSeparator
::
_
NumericLiteral ::
DecimalLiteral
DecimalBigIntegerLiteral
NonDecimalIntegerLiteral [+Sep]
NonDecimalIntegerLiteral [+Sep]
BigIntLiteralSuffix
LegacyOctalIntegerLiteral
DecimalBigIntegerLiteral
::
0
BigIntLiteralSuffix
NonZeroDigit
DecimalDigits [+Sep] opt
BigIntLiteralSuffix
NonZeroDigit
NumericLiteralSeparator
DecimalDigits [+Sep]
BigIntLiteralSuffix
NonDecimalIntegerLiteral [Sep]
::
BinaryIntegerLiteral [?Sep]
OctalIntegerLiteral [?Sep]
HexIntegerLiteral [?Sep]
BigIntLiteralSuffix
::
n
DecimalLiteral ::
DecimalIntegerLiteral
.
DecimalDigits [+Sep] opt
ExponentPart [+Sep] opt
.
DecimalDigits [+Sep]
ExponentPart [+Sep] opt
DecimalIntegerLiteral
ExponentPart [+Sep] opt
DecimalIntegerLiteral
::
0
NonZeroDigit
NonZeroDigit
NumericLiteralSeparator opt
DecimalDigits [+Sep]
NonOctalDecimalIntegerLiteral
DecimalDigits [Sep]
::
DecimalDigit
DecimalDigits [?Sep]
DecimalDigit
[+Sep]
DecimalDigits [+Sep]
NumericLiteralSeparator
DecimalDigit
DecimalDigit ::
one of 0 1 2
3 4 5 6 7
8 9
NonZeroDigit ::
one of 1 2 3
4 5 6 7 8
9
ExponentPart [Sep]
::
ExponentIndicator
SignedInteger [?Sep]
ExponentIndicator
:: one of e
E
SignedInteger [Sep]
::
DecimalDigits [?Sep]
+
DecimalDigits [?Sep]
-
DecimalDigits [?Sep]
BinaryIntegerLiteral [Sep]
::
0b
BinaryDigits [?Sep]
0B
BinaryDigits [?Sep]
BinaryDigits [Sep]
::
BinaryDigit
BinaryDigits [?Sep]
BinaryDigit
[+Sep]
BinaryDigits [+Sep]
NumericLiteralSeparator
BinaryDigit
BinaryDigit ::
one of 0 1
OctalIntegerLiteral [Sep]
::
0o
OctalDigits [?Sep]
0O
OctalDigits [?Sep]
OctalDigits [Sep]
::
OctalDigit
OctalDigits [?Sep]
OctalDigit
[+Sep]
OctalDigits [+Sep]
NumericLiteralSeparator
OctalDigit
LegacyOctalIntegerLiteral
::
0
OctalDigit
LegacyOctalIntegerLiteral
OctalDigit
NonOctalDecimalIntegerLiteral
::
0
NonOctalDigit
LegacyOctalLikeDecimalIntegerLiteral
NonOctalDigit
NonOctalDecimalIntegerLiteral
DecimalDigit
LegacyOctalLikeDecimalIntegerLiteral
::
0
OctalDigit
LegacyOctalLikeDecimalIntegerLiteral
OctalDigit
OctalDigit ::
one of 0 1 2
3 4 5 6
7
NonOctalDigit ::
one of 8 9
HexIntegerLiteral [Sep]
::
0x
HexDigits [?Sep]
0X
HexDigits [?Sep]
HexDigits [Sep]
::
HexDigit
HexDigits [?Sep]
HexDigit
[+Sep]
HexDigits [+Sep]
NumericLiteralSeparator
HexDigit
HexDigit :: one
of 0 1 2
3 4 5 6 7
8 9 a b c
d e f A B
C D E F
SourceCharacter がNumericLiteral の直後に現れる場合、IdentifierStart またはDecimalDigit であってはならない。
注
例えば:3inはエラーであり、入力要素3とinの2つではない。
12.9.3.1 静的セマンティクス: 早期エラー
NumericLiteral ::
LegacyOctalIntegerLiteral
DecimalIntegerLiteral
:: NonOctalDecimalIntegerLiteral
注
12.9.3.2 静的セマンティクス: MV
数値リテラルは、Number型 または
BigInt型
の値を表す。
12.9.3.3 静的セマンティクス: NumericValue
構文指示操作
NumericValueは引数を取らず、NumberまたはBigIntを返す。この操作は、以下の各生成規則に分けて定義される。
NumericLiteral ::
DecimalLiteral
RoundMVResult (DecimalLiteral のMV)
を返す。
NumericLiteral ::
NonDecimalIntegerLiteral
𝔽 (NonDecimalIntegerLiteral のMV)
を返す。
NumericLiteral ::
LegacyOctalIntegerLiteral
𝔽 (LegacyOctalIntegerLiteral のMV)
を返す。
NumericLiteral ::
NonDecimalIntegerLiteral
BigIntLiteralSuffix
BigInt
value for (NonDecimalIntegerLiteral のMV)
を返す。
DecimalBigIntegerLiteral
::
0
BigIntLiteralSuffix
0 ℤ を返す。
DecimalBigIntegerLiteral
::
NonZeroDigit
BigIntLiteralSuffix
BigInt
value for (NonZeroDigit のMV) を返す。
DecimalBigIntegerLiteral
::
NonZeroDigit
DecimalDigits
BigIntLiteralSuffix
NonZeroDigit
NumericLiteralSeparator
DecimalDigits
BigIntLiteralSuffix
n を、DecimalDigits 中の符号位置数(ただし、全てのNumericLiteralSeparator の出現を除外する)とする。
mv を (NonZeroDigit のMV ×
10n ) にDecimalDigits のMVを加えた値とする。
ℤ (mv ) を返す。
12.9.4 文字列リテラル
注1
文字列リテラルは、1つまたは2つの引用符で囲まれた0個以上のUnicode符号位置である。Unicode符号位置はエスケープシーケンスによっても表現できる。すべての符号位置は、閉じ引用符、U+005C(REVERSE
SOLIDUS)、U+000D(CARRIAGE RETURN)、U+000A(LINE
FEED)を除き、文字列リテラル内でリテラルとして現れることができる。どの符号位置もエスケープシーケンスの形で現れることができる。文字列リテラルはECMAScriptのString値として評価される。これらのString値を生成する際、Unicodeの符号位置は11.1.1 で定義されるようにUTF-16でエンコードされる。Basic
Multilingual Planeに属する符号位置は1つのコードユニット要素としてエンコードされる。その他の符号位置は文字列の2つのコードユニット要素としてエンコードされる。
構文
StringLiteral ::
"
DoubleStringCharacters opt
"
'
SingleStringCharacters opt
'
DoubleStringCharacters
::
DoubleStringCharacter
DoubleStringCharacters opt
SingleStringCharacters
::
SingleStringCharacter
SingleStringCharacters opt
DoubleStringCharacter
::
SourceCharacter
but not one of " or \ or LineTerminator
<LS>
<PS>
\
EscapeSequence
LineContinuation
SingleStringCharacter
::
SourceCharacter
but not one of ' or \ or LineTerminator
<LS>
<PS>
\
EscapeSequence
LineContinuation
LineContinuation ::
\
LineTerminatorSequence
EscapeSequence ::
CharacterEscapeSequence
0
[lookahead ∉ DecimalDigit ]
LegacyOctalEscapeSequence
NonOctalDecimalEscapeSequence
HexEscapeSequence
UnicodeEscapeSequence
CharacterEscapeSequence
::
SingleEscapeCharacter
NonEscapeCharacter
SingleEscapeCharacter
:: one of '
" \ b f n
r t v
NonEscapeCharacter
::
SourceCharacter
but not one of EscapeCharacter or LineTerminator
EscapeCharacter ::
SingleEscapeCharacter
DecimalDigit
x
u
LegacyOctalEscapeSequence
::
0
[lookahead ∈ { 8 , 9 }]
NonZeroOctalDigit
[lookahead ∉ OctalDigit ]
ZeroToThree
OctalDigit
[lookahead ∉ OctalDigit ]
FourToSeven
OctalDigit
ZeroToThree
OctalDigit
OctalDigit
NonZeroOctalDigit
::
OctalDigit but
not 0
ZeroToThree ::
one of 0 1 2
3
FourToSeven ::
one of 4 5 6
7
NonOctalDecimalEscapeSequence
:: one of 8
9
HexEscapeSequence
::
x
HexDigit
HexDigit
UnicodeEscapeSequence
::
u
Hex4Digits
u{
CodePoint
}
Hex4Digits ::
HexDigit
HexDigit
HexDigit
HexDigit
非終端記号HexDigit の定義は12.9.3 に与えられている。SourceCharacter は11.1 で定義されている。
注2
<LF>と<CR>は、LineContinuation の一部として空の符号位置列を生成する場合を除き、文字列リテラル中に現れることはできない。どちらかを文字列リテラルのString値に含める正しい方法は、\nや\u000Aのようなエスケープシーケンスを使うことである。
12.9.4.1 静的セマンティクス: 早期エラー
EscapeSequence ::
LegacyOctalEscapeSequence
NonOctalDecimalEscapeSequence
注1
注2
文字列リテラルがUse Strict
Directive より前に現れ、その囲むコードをstrict
mode にすることがあり、このようなリテラルに対して上記の規則を厳密に適用する必要がある。例えば、次のソーステキストは構文エラーとなる:
function invalid ( ) { "\7" ; "use strict" ; }
12.9.4.2 静的セマンティクス: SV
構文指示操作 SVは引数を取らず、Stringを返す。
文字列リテラルはString型 の値を表す。SVは、文字列リテラルの各部分への再帰的な適用によって、文字列リテラルに対するString値を生成する。この過程の一部として、文字列リテラル内の一部のUnicode符号位置は、下記または12.9.3 で述べるように数学的値 を持つものとして解釈される。
表37: 文字列 単一文字エスケープシーケンス
エスケープシーケンス
コードユニット値
Unicode文字名
記号
\b
0x0008
バックスペース
<BS>
\t
0x0009
水平タブ
<HT>
\n
0x000A
ラインフィード(LF)
<LF>
\v
0x000B
垂直タブ
<VT>
\f
0x000C
フォームフィード(FF)
<FF>
\r
0x000D
キャリッジリターン(CR)
<CR>
\"
0x0022
引用符(ダブルクォート)
"
\'
0x0027
アポストロフィ
'
\\
0x005C
リバースソリダス
\
12.9.4.3 静的セマンティクス: MV
12.9.5 正規表現リテラル
注 1
正規表現リテラルは、評価されるたびに RegExp オブジェクト(22.2
を参照)へ変換される入力要素である。プログラム内の2つの正規表現リテラルは、たとえ内容が同一であっても、評価されると ===
で決して等しくならない正規表現オブジェクトになる。また、RegExp オブジェクトは new RegExp によって、または RegExp
コンストラクター を関数として呼び出すことによっても実行時に作成できる(22.2.4 を参照)。
以下の生成規則は、正規表現リテラルの構文を表現しており、入力要素スキャナーによって正規表現リテラルの終端を検出するために使用される。RegularExpressionBody および RegularExpressionFlags
を構成するソーステキストは、その後、より厳密な ECMAScript 正規表現文法(22.2.1 )を用いて再度構文解析される。
実装は 22.2.1
で定義された ECMAScript 正規表現文法を拡張してもよいが、以下で定義される RegularExpressionBody および RegularExpressionFlags
の生成規則や、それらが使用する生成規則を拡張してはならない。
構文
RegularExpressionLiteral
::
/
RegularExpressionBody
/
RegularExpressionFlags
RegularExpressionBody
::
RegularExpressionFirstChar
RegularExpressionChars
RegularExpressionChars
::
[empty]
RegularExpressionChars
RegularExpressionChar
RegularExpressionFirstChar
::
RegularExpressionNonTerminator
ただし * 、\ 、/ 、[
のいずれでもない
RegularExpressionBackslashSequence
RegularExpressionClass
RegularExpressionChar
::
RegularExpressionNonTerminator
ただし \ 、/ 、[ のいずれでもない
RegularExpressionBackslashSequence
RegularExpressionClass
RegularExpressionBackslashSequence
::
\
RegularExpressionNonTerminator
RegularExpressionNonTerminator
::
SourceCharacter
LineTerminator でないもの
RegularExpressionClass
::
[
RegularExpressionClassChars
]
RegularExpressionClassChars
::
[empty]
RegularExpressionClassChars
RegularExpressionClassChar
RegularExpressionClassChar
::
RegularExpressionNonTerminator
ただし ] 、\ のいずれでもない
RegularExpressionBackslashSequence
RegularExpressionFlags
::
[empty]
RegularExpressionFlags
IdentifierPartChar
注 2
正規表現リテラルは空にすることはできない。空の正規表現リテラルの代わりに、コードユニット列 //
は単一行コメントの開始になる。空の正規表現を指定したい場合は /(?:)/ を使用すること。
12.9.5.1 静的セマンティクス: BodyText
構文指向操作
BodyText は引数を取らずソーステキストを返す。次の生成規則ごとに分割して定義される。
RegularExpressionLiteral
::
/
RegularExpressionBody
/
RegularExpressionFlags
RegularExpressionBody
として認識されたソーステキストを返す。
12.9.5.2 静的セマンティクス: FlagText
構文指向操作
FlagText は引数を取らずソーステキストを返す。次の生成規則ごとに分割して定義される。
RegularExpressionLiteral
::
/
RegularExpressionBody
/
RegularExpressionFlags
RegularExpressionFlags
として認識されたソーステキストを返す。
12.9.6 テンプレートリテラルの字句要素
構文
Template ::
NoSubstitutionTemplate
TemplateHead
NoSubstitutionTemplate
::
`
TemplateCharacters opt
`
TemplateHead ::
`
TemplateCharacters opt
${
TemplateSubstitutionTail
::
TemplateMiddle
TemplateTail
TemplateMiddle ::
}
TemplateCharacters opt
${
TemplateTail ::
}
TemplateCharacters opt
`
TemplateCharacters
::
TemplateCharacter
TemplateCharacters opt
TemplateCharacter
::
$
[先読み ≠ { ]
\
TemplateEscapeSequence
\
NotEscapeSequence
LineContinuation
LineTerminatorSequence
SourceCharacter
ただし ` 、\ 、$ 、または
LineTerminator
のいずれでもない
TemplateEscapeSequence
::
CharacterEscapeSequence
0
[先読み ∉ DecimalDigit ]
HexEscapeSequence
UnicodeEscapeSequence
NotEscapeSequence
::
0
DecimalDigit
DecimalDigit
0 でないもの
x
[先読み ∉ HexDigit ]
x
HexDigit
[先読み ∉ HexDigit ]
u
[先読み ∉ HexDigit ]
[先読み ≠ { ]
u
HexDigit
[先読み ∉ HexDigit ]
u
HexDigit
HexDigit
[先読み ∉ HexDigit ]
u
HexDigit
HexDigit
HexDigit
[先読み ∉ HexDigit ]
u
{
[先読み ∉ HexDigit ]
u
{
NotCodePoint
[先読み ∉ HexDigit ]
u
{
CodePoint
[先読み ∉ HexDigit ]
[先読み ≠ } ]
NotCodePoint ::
HexDigits [~Sep]
ただし HexDigits
のMVが0x10FFFFより大きい場合のみ
CodePoint ::
HexDigits [~Sep]
ただし HexDigits
のMVが0x10FFFF以下の場合のみ
注
12.9.6.1 静的セマンティクス: TV
構文指向操作
TV は引数を取らず、String または
undefined を返す。テンプレートリテラルの構成要素は、TV によって
String 型
の値として解釈される。TV は
テンプレートオブジェクト(いわゆるテンプレート値)のインデックス付き要素を構築するために使用される。TV では、エスケープシーケンスは
それが表す Unicode コードポイントの UTF-16 コード単位に置き換えられる。
12.9.6.2 静的セマンティクス: TRV
構文指向操作
TRV は引数を取らず、String を返す。テンプレートリテラルの構成要素は、TRV によって String 型
の値として解釈される。TRV はテンプレートオブジェクト(いわゆるテンプレートの raw 値)の「生」の要素を構築するために使用される。TRV は TV と似ているが、TRV
ではエスケープシーケンスがリテラルで現れる通りに解釈される点が異なる。
注
TV は
LineContinuation のコード単位を除外するが、TRV
はそれらを含む。<CR><LF> および <CR> LineTerminatorSequence は、
TV および TRV の両方で <LF>
に正規化される。<CR> または <CR><LF> シーケンスを含めるには明示的に
TemplateEscapeSequence
が必要となる。
12.10 自動セミコロン挿入
ほとんどの ECMAScript
文および宣言はセミコロンで終わらなければならない。こうしたセミコロンはソーステキストに明示的に記述することが常にできる。しかし利便性のため、特定の場合にはソーステキストからこうしたセミコロンを省略できる。これらの場合は、その場面でセミコロンがソースコードのトークンストリームに自動的に挿入されると説明される。
12.10.1 自動セミコロン挿入の規則
以下の規則において、「トークン」は、ゴール記号 として現在の字句的
12
で説明されるように認識された実際の字句トークンを指す。
セミコロン挿入には3つの基本規則がある:
左から右にソーステキストを構文解析しているとき、文法のいかなる生成規則にも許されていないトークン(問題のあるトークン )が現れた場合、以下のいずれかが真であれば、その問題のあるトークンの直前にセミコロンが自動的に挿入される:
問題のあるトークンが、直前のトークンと少なくとも1つの LineTerminator で区切られている場合。
問題のあるトークンが } である場合。
直前のトークンが ) であり、挿入されたセミコロンが do-while 文の終端セミコロンとして構文解析される場合(14.7.2 )。
左から右にソーステキストを構文解析しているとき、トークンストリームの終端に達し、パーサーが入力トークンストリームをゴール非終端記号の単一インスタンスとして構文解析できない場合、入力ストリームの末尾にセミコロンが自動的に挿入される。
左から右にソーステキストを構文解析しているとき、文法のいずれかの生成規則で許可されているトークンが現れたが、その生成規則が制限付き生成規則 であり、トークンがその制限付き生成規則内の「[no
LineTerminator
here]」注釈の直後に来る終端記号や非終端記号の最初のトークン(したがってそのトークンは制限付きトークンと呼ばれる)であり、制限付きトークンが直前のトークンと少なくとも1つの
LineTerminator
で区切られている場合、その制限付きトークンの直前にセミコロンが自動的に挿入される。
ただし、上記規則には追加の優先条件がある:自動的に挿入されたセミコロンが空文として構文解析される場合や、そのセミコロンが for
文のヘッダ内の2つのセミコロンのうちの1つになる場合(14.7.4 参照)、セミコロンは自動的に挿入されない。
注
以下は文法における唯一の制限付き生成規則である:
UpdateExpression [Yield,
Await] :
LeftHandSideExpression [?Yield,
?Await]
[no LineTerminator
here]
++
LeftHandSideExpression [?Yield,
?Await]
[no LineTerminator
here]
--
ContinueStatement [Yield,
Await] :
continue
;
continue
[no LineTerminator
here]
LabelIdentifier [?Yield,
?Await]
;
BreakStatement [Yield,
Await] :
break
;
break
[no LineTerminator
here]
LabelIdentifier [?Yield,
?Await]
;
ReturnStatement [Yield,
Await] :
return
;
return
[no LineTerminator
here]
Expression [+In,
?Yield, ?Await]
;
ThrowStatement [Yield,
Await] :
throw
[no LineTerminator
here]
Expression [+In,
?Yield, ?Await]
;
YieldExpression [In,
Await] :
yield
yield
[no LineTerminator
here]
AssignmentExpression [?In,
+Yield, ?Await]
yield
[no LineTerminator
here]
*
AssignmentExpression [?In,
+Yield, ?Await]
ArrowFunction [In,
Yield, Await] :
ArrowParameters [?Yield,
?Await]
[no LineTerminator
here]
=>
ConciseBody [?In]
AsyncFunctionDeclaration [Yield,
Await, Default] :
async
[no LineTerminator
here]
function
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
[+Default]
async
[no LineTerminator
here]
function
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
[no LineTerminator
here]
function
BindingIdentifier [~Yield,
+Await] opt
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncMethod [Yield,
Await] :
async
[no LineTerminator
here]
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncGeneratorDeclaration [Yield,
Await, Default] :
async
[no LineTerminator
here]
function
*
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
[+Default]
async
[no LineTerminator
here]
function
*
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
[no LineTerminator
here]
function
*
BindingIdentifier [+Yield,
+Await] opt
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorMethod [Yield,
Await] :
async
[no LineTerminator
here]
*
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncArrowFunction [In,
Yield, Await] :
async
[no LineTerminator
here]
AsyncArrowBindingIdentifier [?Yield]
[no LineTerminator
here]
=>
AsyncConciseBody [?In]
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
[no LineTerminator
here]
=>
AsyncConciseBody [?In]
AsyncArrowHead
:
async
[no LineTerminator
here]
ArrowFormalParameters [~Yield,
+Await]
これらの制限付き生成規則の実質的な効果は次のとおりである:
パーサーが後置演算子として ++ または -- トークンを解釈する箇所で、その直前のトークンと
++ または -- トークンの間に少なくとも1つの LineTerminator
が現れた場合、++ または -- トークンの直前にセミコロンが自動的に挿入される。
continue、break、return、throw、yield
トークンが現れ、その次のトークンの前に LineTerminator
が現れる場合、continue、break、return、throw、yield
トークンの直後にセミコロンが自動的に挿入される。
アロー関数のパラメータの後に LineTerminator
があり、=> トークンの前に来る場合、セミコロンが自動的に挿入され、その句読点は構文エラーとなる。
async トークンの後に LineTerminator があり、その後に
function または IdentifierName または (
トークンが続く場合、セミコロンが自動的に挿入され、async トークンは続くトークンと同じ式やクラス要素の一部とはみなされない。
async トークンの後に LineTerminator があり、その後に
* トークンが続く場合、セミコロンが自動的に挿入され、その句読点は構文エラーとなる。
このことから ECMAScript プログラマへの実践的な助言は次のとおりである:
後置 ++ や -- 演算子は被演算子と同じ行に書くこと。
return や throw 文の Expression 、yield 式の
AssignmentExpression
は、return、throw、yield トークンと同じ行に開始すること。
break や continue 文の LabelIdentifier
は、それぞれのトークンと同じ行に書くこと。
アロー関数のパラメータ終端と => は同じ行に書くこと。
非同期関数やメソッドの前の async トークンは、直後のトークンと同じ行に書くこと。
12.10.2 自動セミコロン挿入の例
この節は規範的ではない。
次のソース
{ 1 2 } 3
は、自動セミコロン挿入規則があっても ECMAScript 文法上有効な文ではない。対照的に、次のソース
{ 1
2 } 3
も ECMAScript 文としては有効ではないが、自動セミコロン挿入によって次のように変換される:
{ 1
;2 ;} 3 ;
これは ECMAScript 文として有効である。
次のソース
for (a; b
)
は ECMAScript 文として有効ではなく、自動セミコロン挿入でも変化しない。なぜなら for 文のヘッダのセミコロンが必要だからである。自動セミコロン挿入は
for 文のヘッダ内の2つのセミコロンのいずれかを決して挿入しない。
次のソース
return
a + b
は自動セミコロン挿入によって次のように変換される:
return ;
a + b;
注 1
式 a + b は return 文の戻り値として扱われない。なぜなら LineTerminator が return
トークンとそれを区切っているからである。
次のソース
a = b
++c
は自動セミコロン挿入によって次のように変換される:
a = b;
++c;
注 2
トークン ++ は変数 b への後置演算子として扱われない。なぜなら LineTerminator が b と
++ の間にあるからである。
次のソース
if (a > b)
else c = d
は ECMAScript 文として有効ではなく、else
トークンの前で自動セミコロン挿入によって変更されることもない。なぜなら、その時点で文法のいかなる生成規則も適用できないが、自動的に挿入されたセミコロンが空文として構文解析されるためである。
次のソース
a = b + c
(d + e).print ()
は自動セミコロン挿入によって変換されない 。なぜなら2行目の括弧で始まる式が、関数呼び出しの引数リストとみなされるからである:
a = b + c (d + e).print ()
代入文が左括弧で始まる場合、先行する文の末尾には自動セミコロン挿入に頼らず、明示的にセミコロンを記述するのがよい。
12.10.3 自動セミコロン挿入の興味深いケース
この節は規範的ではない。
ECMAScript
プログラムは自動セミコロン挿入に頼ることで、非常に少ないセミコロンで記述できる。上述のとおり、セミコロンはすべての改行で挿入されるわけではなく、自動セミコロン挿入は複数のトークンや行終端子を跨いで作用することがある。
ECMAScript に新しい構文機能が追加されると、自動セミコロン挿入の前に構文規則が変わるような追加の文法生成規則が加わる可能性がある。
この節の目的上、自動セミコロン挿入のケースが「興味深い」と見なされるのは、直前のソーステキストによってセミコロンが挿入されるかどうかが変わる場所である。この節の残りでは、この
ECMAScript バージョンにおける自動セミコロン挿入の興味深いケースをいくつか説明する。
12.10.3.1 文リストにおける自動セミコロン挿入の興味深いケース
StatementList では、多くの
StatementListItem
の末尾にセミコロンが必要だが、自動セミコロン挿入によって省略可能である。上記の規則の結果として、式で終わる行の直後の行が以下のいずれかで始まる場合、セミコロンが必要となる:
12.10.3.2 自動セミコロン挿入と「[no LineTerminator here]」のケース
この節は規範的ではない。
ECMAScript には「[no LineTerminator
here]」を含む文法生成規則がある。これらの生成規則は文法上のオペランドをオプションにするための手段となることがある。これらの箇所に LineTerminator
を挿入すると、オプションのオペランドなしの文法生成規則が適用されることになる。
この節の残りでは、この ECMAScript バージョンで「[no LineTerminator here]」を用いる生成規則をいくつか説明する。
12.10.3.2.1 オペランドがオプションで「[no LineTerminator here]」を持つ文法生成規則一覧
13 ECMAScript言語:式(Expressions)
13.1 識別子(Identifiers)
構文
IdentifierReference [Yield,
Await] :
Identifier
[~Yield]
yield
[~Await]
await
BindingIdentifier [Yield,
Await] :
Identifier
yield
await
LabelIdentifier [Yield,
Await] :
Identifier
[~Yield]
yield
[~Await]
await
Identifier :
IdentifierName
ただしReservedWord は除く
注
yield および await は文法上BindingIdentifier として許可されているが、下記の静的意味論 により禁止されており、例えば次のような場合の自動セミコロン挿入を防ぐためである。
let
await 0 ;
13.1.1 静的意味論:早期エラー(Early Errors)
BindingIdentifier
: Identifier
IdentifierReference
: yield
BindingIdentifier
: yield
LabelIdentifier :
yield
IdentifierReference
: await
BindingIdentifier
: await
LabelIdentifier :
await
BindingIdentifier [Yield,
Await] : yield
この生成規則が [Yield] パラメータを持つ場合、構文エラーである。
BindingIdentifier [Yield,
Await] : await
この生成規則が [Await] パラメータを持つ場合、構文エラーである。
IdentifierReference [Yield,
Await] : Identifier
BindingIdentifier [Yield,
Await] : Identifier
LabelIdentifier [Yield,
Await] : Identifier
Identifier : IdentifierName ただし
ReservedWord は除く
注
IdentifierName の
StringValue は、IdentifierName 内の
Unicode エスケープシーケンスを正規化するため、そのようなエスケープを使用して Identifier のコードポイント列が ReservedWord
と同じになるように記述することはできない。
13.1.2 静的意味論:StringValue
構文指向操作
StringValue は引数をとらず、String を返す。次の生成規則ごとに定義される:
IdentifierName ::
IdentifierStart
IdentifierName
IdentifierPart
idTextUnescaped を、IdentifierName の IdentifierCodePoints とする。
CodePointsToString (idTextUnescaped )
を返す。
IdentifierReference
: yield
BindingIdentifier
: yield
LabelIdentifier :
yield
"yield" を返す。
IdentifierReference
: await
BindingIdentifier
: await
LabelIdentifier :
await
"await" を返す。
Identifier : IdentifierName ただし
ReservedWord は除く
IdentifierName の
StringValue を返す。
PrivateIdentifier
::
#
IdentifierName
0x0023(番号記号)と、IdentifierName の StringValue の string-concatenation を返す。
ModuleExportName :
StringLiteral
StringLiteral の
SV
を返す。
13.1.3 実行時意味論:評価(Evaluation)
IdentifierReference
: Identifier
Identifier の StringValue
を引数として、ResolveBinding (...) を返す。
IdentifierReference
: yield
ResolveBinding ("yield" )
を返す。
IdentifierReference
: await
ResolveBinding ("await" )
を返す。
注1
IdentifierReference の評価結果は常に
Reference 型の値となる。
注2
非厳格コード では、キーワード yield
を識別子として使用できる。IdentifierReference
の評価は、yield のバインディングを Identifier として解決する。早期エラー制約により、このような評価は
非厳格コード でのみ発生することが保証される。
13.2 基本式(Primary Expression)
構文
PrimaryExpression [Yield,
Await] :
this
IdentifierReference [?Yield,
?Await]
Literal
ArrayLiteral [?Yield,
?Await]
ObjectLiteral [?Yield,
?Await]
FunctionExpression
ClassExpression [?Yield,
?Await]
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral [?Yield,
?Await, ~Tagged]
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList [Yield,
Await] :
(
Expression [+In, ?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
)
(
)
(
...
BindingIdentifier [?Yield,
?Await]
)
(
...
BindingPattern [?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
...
BindingIdentifier [?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
...
BindingPattern [?Yield,
?Await]
)
補助構文
次の生成規則のインスタンスを処理する際、
PrimaryExpression [Yield,
Await] : CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList
の解釈は、次の文法を用いて詳細化される:
ParenthesizedExpression [Yield,
Await] :
(
Expression [+In, ?Yield,
?Await]
)
13.2.1 this キーワード
13.2.1.1 実行時意味論:評価
PrimaryExpression
: this
Return ? ResolveThisBinding () を返す。
13.2.2 識別子参照
13.1
を参照。IdentifierReference 。
13.2.3 リテラル
構文
Literal :
NullLiteral
BooleanLiteral
NumericLiteral
StringLiteral
13.2.3.1 実行時意味論:評価
Literal : NullLiteral
null を返す。
Literal : BooleanLiteral
BooleanLiteral
がトークン false の場合、false を返す。
BooleanLiteral
がトークン true の場合、true を返す。
Literal : NumericLiteral
NumericLiteral の
NumericValue を、12.9.3 で定義されている通りに返す。
Literal : StringLiteral
StringLiteral の
SV を、12.9.4.2 で定義されている通りに返す。
13.2.4 配列初期化子
注
ArrayLiteral
は、配列の初期化を記述する式であり、ゼロ個以上の配列要素を表す式のリストを角括弧で囲んで記述される。各要素はリテラルである必要はなく、配列初期化子が評価されるたびに評価される。
配列要素は、要素リストの先頭、中間、末尾で省略することができる。要素リスト内のコンマが AssignmentExpression
に先行されていない場合(すなわち、先頭や他のコンマの後にある場合)、欠落した配列要素は配列の長さに寄与し、後続の要素のインデックスを増加させる。省略された配列要素は未定義である。配列の末尾で要素が省略された場合、その要素は配列の長さに寄与しない。
構文
ArrayLiteral [Yield,
Await] :
[
Elision opt
]
[
ElementList [?Yield,
?Await]
]
[
ElementList [?Yield,
?Await]
,
Elision opt
]
ElementList [Yield,
Await] :
Elision opt
AssignmentExpression [+In,
?Yield, ?Await]
Elision opt
SpreadElement [?Yield,
?Await]
ElementList [?Yield,
?Await]
,
Elision opt
AssignmentExpression [+In,
?Yield, ?Await]
ElementList [?Yield,
?Await]
,
Elision opt
SpreadElement [?Yield,
?Await]
Elision :
,
Elision
,
SpreadElement [Yield,
Await] :
...
AssignmentExpression [+In,
?Yield, ?Await]
13.2.4.1 実行時意味論:ArrayAccumulation
構文指向操作
ArrayAccumulation は、引数 array (配列)および nextIndex (整数 )を取り、通常完了(normal
completion) で 整数 または 急激な完了(abrupt
completion) を返す。次の生成規則ごとに定義される:
Elision : ,
len を nextIndex + 1 とする。
? Set (array ,
"length" , 𝔽 (len ), true )
を実行する。
注:上記のステップは len が 232 - 1 を超える場合に例外を投げる。
len を返す。
Elision :
Elision
,
? ArrayAccumulation の Elision に array
および (nextIndex + 1) を引数として呼び出し、その結果を返す。
ElementList :
Elision opt
AssignmentExpression
Elision が存在する場合、
nextIndex を ? ArrayAccumulation の Elision に
array および nextIndex を引数として呼び出した結果に設定する。
initResult を ? Evaluation の
AssignmentExpression
による評価結果とする。
initValue を ? GetValue (initResult ) とする。
! CreateDataPropertyOrThrow (array ,
! ToString (𝔽 (nextIndex )),
initValue ) を実行する。
nextIndex + 1 を返す。
ElementList :
Elision opt
SpreadElement
Elision が存在する場合、
nextIndex を ? ArrayAccumulation の Elision に
array および nextIndex を引数として呼び出した結果に設定する。
? ArrayAccumulation の SpreadElement に
array および nextIndex を引数として呼び出した結果を返す。
ElementList :
ElementList
,
Elision opt
AssignmentExpression
nextIndex を ? ArrayAccumulation の ElementList に
array および nextIndex を引数として呼び出した結果に設定する。
Elision が存在する場合、
nextIndex を ? ArrayAccumulation の Elision に
array および nextIndex を引数として呼び出した結果に設定する。
initResult を ? Evaluation の
AssignmentExpression
による評価結果とする。
initValue を ? GetValue (initResult ) とする。
! CreateDataPropertyOrThrow (array ,
! ToString (𝔽 (nextIndex )),
initValue ) を実行する。
nextIndex + 1 を返す。
ElementList :
ElementList
,
Elision opt
SpreadElement
nextIndex を ? ArrayAccumulation の ElementList に
array および nextIndex を引数として呼び出した結果に設定する。
Elision が存在する場合、
nextIndex を ? ArrayAccumulation の Elision に
array および nextIndex を引数として呼び出した結果に設定する。
? ArrayAccumulation の SpreadElement に
array および nextIndex を引数として呼び出した結果を返す。
SpreadElement :
...
AssignmentExpression
spreadRef を ? Evaluation の
AssignmentExpression
による評価結果とする。
spreadObj を ? GetValue (spreadRef ) とする。
iteratorRecord を ? GetIterator (spreadObj ,
sync ) とする。
繰り返し、
next を ? IteratorStepValue (iteratorRecord )
とする。
next が done であれば、nextIndex を返す。
! CreateDataPropertyOrThrow (array ,
! ToString (𝔽 (nextIndex )),
next ) を実行する。
nextIndex を nextIndex + 1 に設定する。
注
CreateDataPropertyOrThrow
は、標準の組み込み Array
プロトタイプオブジェクト が修正されて [[Set]]
による新しい自身のプロパティの作成ができない場合でも、配列に自身のプロパティを定義できるようにするために使用される。
13.2.4.2 実行時意味論:評価
ArrayLiteral :
[
Elision opt
]
array を ! ArrayCreate (0) とする。
Elision が存在する場合、
? ArrayAccumulation の Elision に
array および 0 を引数として呼び出す。
array を返す。
ArrayLiteral :
[
ElementList
]
array を ! ArrayCreate (0) とする。
? ArrayAccumulation の ElementList に
array および 0 を引数として呼び出す。
array を返す。
ArrayLiteral :
[
ElementList
,
Elision opt
]
array を ! ArrayCreate (0) とする。
nextIndex を ? ArrayAccumulation の ElementList に
array および 0 を引数として呼び出した結果に設定する。
Elision が存在する場合、
? ArrayAccumulation の Elision に
array および nextIndex を引数として呼び出す。
array を返す。
13.2.5 オブジェクト初期化子
注1
オブジェクト初期化子は、リテラルに似た形式で記述されるオブジェクトの初期化を表す式である。ゼロ個以上の プロパティキー
と対応する値のペアを中括弧で囲んで記述する。値はリテラルでなくてもよく、オブジェクト初期化子が評価されるたびに評価される。
構文
ObjectLiteral [Yield,
Await] :
{
}
{
PropertyDefinitionList [?Yield,
?Await]
}
{
PropertyDefinitionList [?Yield,
?Await]
,
}
PropertyDefinitionList [Yield,
Await] :
PropertyDefinition [?Yield,
?Await]
PropertyDefinitionList [?Yield,
?Await]
,
PropertyDefinition [?Yield,
?Await]
PropertyDefinition [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
CoverInitializedName [?Yield,
?Await]
PropertyName [?Yield,
?Await]
:
AssignmentExpression [+In,
?Yield, ?Await]
MethodDefinition [?Yield,
?Await]
...
AssignmentExpression [+In,
?Yield, ?Await]
PropertyName [Yield,
Await] :
LiteralPropertyName
ComputedPropertyName [?Yield,
?Await]
LiteralPropertyName
:
IdentifierName
StringLiteral
NumericLiteral
ComputedPropertyName [Yield,
Await] :
[
AssignmentExpression [+In,
?Yield, ?Await]
]
CoverInitializedName [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await]
Initializer [In, Yield,
Await] :
=
AssignmentExpression [?In,
?Yield, ?Await]
注2
注3
特定の文脈では、ObjectLiteral
は、より制限された二次文法をカバーするカバ―文法として使用される。CoverInitializedName
生成規則は、これらの二次文法を完全にカバーするために必要である。しかし、この生成規則の使用は、実際の ObjectLiteral が期待される通常の文脈では早期構文エラーとなる。
13.2.5.1 静的意味論:早期エラー
PropertyDefinition
: MethodDefinition
実際のオブジェクト初期化子を記述することに加えて、ObjectLiteral の生成規則は ObjectAssignmentPattern
のカバ―文法としても使われ、CoverParenthesizedExpressionAndArrowParameterList
の一部として認識されることがある。ObjectLiteral が ObjectAssignmentPattern
が必要な文脈で現れる場合、以下の早期エールールは適用されない 。また、最初に CoverParenthesizedExpressionAndArrowParameterList
または CoverCallExpressionAndAsyncArrowHead
を構文解析する場合にも適用されない。
PropertyDefinition
: CoverInitializedName
この生成規則に一致するソーステキストがある場合、構文エラーである。
注1
この生成規則は、ObjectLiteral が ObjectAssignmentPattern
のカバ―文法として機能できるように存在する。実際のオブジェクト初期化子には現れない。
ObjectLiteral :
{
PropertyDefinitionList
}
{
PropertyDefinitionList
,
}
注2
13.2.5.2 静的意味論:IsComputedPropertyKey
構文指向操作
IsComputedPropertyKey は引数を取らず、Boolean を返す。次の生成規則ごとに定義される:
PropertyName :
LiteralPropertyName
false を返す。
PropertyName :
ComputedPropertyName
true を返す。
13.2.5.3 静的意味論:PropertyNameList
構文指向操作
PropertyNameList は引数を取らず、String の List
を返す。次の生成規則ごとに定義される:
PropertyDefinitionList
: PropertyDefinition
propName を PropertyDefinition の PropName とする。
propName が empty の場合、新しい空の List を返す。
« propName » を返す。
PropertyDefinitionList
:
PropertyDefinitionList
,
PropertyDefinition
list を PropertyDefinitionList の
PropertyNameList
とする。
propName を PropertyDefinition の PropName とする。
propName が empty の場合、list を返す。
list と « propName » の list-concatenation を返す。
13.2.5.4 実行時意味論:評価
ObjectLiteral :
{
}
OrdinaryObjectCreate (%Object.prototype% )
を返す。
ObjectLiteral :
{
PropertyDefinitionList
}
{
PropertyDefinitionList
,
}
obj を OrdinaryObjectCreate (%Object.prototype% )
とする。
? PropertyDefinitionEvaluation の PropertyDefinitionList に引数
obj で実行する。
obj を返す。
LiteralPropertyName
: IdentifierName
IdentifierName の
StringValue を返す。
LiteralPropertyName
: StringLiteral
StringLiteral の
SV を返す。
LiteralPropertyName
: NumericLiteral
nbr を NumericLiteral の NumericValue とする。
! ToString (nbr ) を返す。
ComputedPropertyName
:
[
AssignmentExpression
]
exprValue を ? Evaluation の
AssignmentExpression
による評価結果とする。
propName を ? GetValue (exprValue ) とする。
? ToPropertyKey (propName ) を返す。
13.2.5.5 実行時意味論:PropertyDefinitionEvaluation
構文指向操作
PropertyDefinitionEvaluation は引数
object (オブジェクト)をとり、unused
を含む通常完了 または 急激な完了
を返す。次の生成規則ごとに定義される:
PropertyDefinitionList
:
PropertyDefinitionList
,
PropertyDefinition
? PropertyDefinitionEvaluation の PropertyDefinitionList に引数
object で実行する。
? PropertyDefinitionEvaluation の PropertyDefinition に引数
object で実行する。
unused を返す。
PropertyDefinition
:
...
AssignmentExpression
exprValue を ? Evaluation の
AssignmentExpression
による評価結果とする。
fromValue を ? GetValue (exprValue ) とする。
excludedNames を新しい空の List とする。
? CopyDataProperties (object ,
fromValue , excludedNames ) を実行する。
unused を返す。
PropertyDefinition
: IdentifierReference
propName を IdentifierReference の
StringValue とする。
exprValue を ? Evaluation の
IdentifierReference
による評価結果とする。
propValue を ? GetValue (exprValue ) とする。
Assert :
object は通常の拡張可能なオブジェクトであり、非設定可能プロパティを持たない。
! CreateDataPropertyOrThrow (object ,
propName , propValue ) を実行する。
unused を返す。
PropertyDefinition
:
PropertyName
:
AssignmentExpression
propKey を ? Evaluation の
PropertyName
による評価結果とする。
この PropertyDefinition が ParseJSON 用に評価されている Script に含まれる場合、
isProtoSetter を false とする。
そうでなく、propKey が "__proto__" かつ PropertyName の
IsComputedPropertyKey
が false の場合、
isProtoSetter を true とする。
その他の場合、
isProtoSetter を false とする。
IsAnonymousFunctionDefinition (AssignmentExpression ) が
true かつ isProtoSetter が false の場合、
propValue を ? NamedEvaluation の AssignmentExpression
に引数 propKey で実行した結果とする。
そうでない場合、
exprValueRef を ? Evaluation の AssignmentExpression
による評価結果とする。
propValue を ? GetValue (exprValueRef )
とする。
isProtoSetter が true の場合、
propValue が オブジェクト であるか、または
propValue が null の場合、
! object .[[SetPrototypeOf]] (propValue )
を実行する。
unused を返す。
Assert :
object は通常の拡張可能なオブジェクトであり、非設定可能プロパティを持たない。
! CreateDataPropertyOrThrow (object ,
propKey , propValue ) を実行する。
unused を返す。
PropertyDefinition
: MethodDefinition
? MethodDefinitionEvaluation の MethodDefinition
に引数 object および true で実行する。
unused を返す。
13.2.6 関数定義式
PrimaryExpression
: FunctionExpression
については、15.2 を参照。
PrimaryExpression
: GeneratorExpression
については、15.5 を参照。
PrimaryExpression
: ClassExpression
については、15.7 を参照。
PrimaryExpression
: AsyncFunctionExpression
については、15.8 を参照。
PrimaryExpression
: AsyncGeneratorExpression
については、15.6 を参照。
13.2.7 正規表現リテラル
構文
12.9.5 を参照。
13.2.7.1 静的意味論:早期エラー
PrimaryExpression
: RegularExpressionLiteral
13.2.7.2 静的意味論:IsValidRegularExpressionLiteral (
literal )
抽象操作 IsValidRegularExpressionLiteral は、引数 literal (RegularExpressionLiteral
構文ノード )を取り、Boolean
を返す。その引数が有効な正規表現リテラルであるかどうかを判定する。呼び出されたとき、以下の手順を実行する:
flags を literal の FlagText とする。
flags に
d、g、i、m、s、u、v、y
以外のコードポイントが含まれている場合、または flags
に同じコードポイントが複数回含まれている場合、false を返す。
flags に u が含まれている場合、u を true
とし、そうでなければ false とする。
flags に v が含まれている場合、v を true
とし、そうでなければ false とする。
patternText を literal の BodyText
とする。
u が false かつ v が false
の場合、
stringValue を CodePointsToString (patternText )
とする。
patternText を stringValue の各16ビット要素を Unicode BMP
コードポイントとして解釈したコードポイント列に設定する。UTF-16 デコードは行わない。
parseResult を ParsePattern (patternText ,
u , v ) とする。
parseResult が 構文ノード
である場合、true を返す。そうでなければ false を返す。
13.2.7.3 実行時意味論:評価
PrimaryExpression
: RegularExpressionLiteral
pattern を CodePointsToString (BodyText of RegularExpressionLiteral )
とする。
flags を CodePointsToString (FlagText of RegularExpressionLiteral )
とする。
! RegExpCreate (pattern ,
flags ) を返す。
13.2.8 テンプレートリテラル
構文
TemplateLiteral [Yield, Await,
Tagged] :
NoSubstitutionTemplate
SubstitutionTemplate [?Yield,
?Await, ?Tagged]
SubstitutionTemplate [Yield,
Await, Tagged] :
TemplateHead
Expression [+In, ?Yield,
?Await]
TemplateSpans [?Yield,
?Await, ?Tagged]
TemplateSpans [Yield, Await,
Tagged] :
TemplateTail
TemplateMiddleList [?Yield,
?Await, ?Tagged]
TemplateTail
TemplateMiddleList [Yield,
Await, Tagged] :
TemplateMiddle
Expression [+In, ?Yield,
?Await]
TemplateMiddleList [?Yield,
?Await, ?Tagged]
TemplateMiddle
Expression [+In, ?Yield,
?Await]
13.2.8.1 静的意味論:早期エラー
TemplateLiteral [Yield,
Await, Tagged] :
NoSubstitutionTemplate
TemplateLiteral [Yield,
Await, Tagged] :
SubstitutionTemplate [?Yield,
?Await, ?Tagged]
SubstitutionTemplate [Yield,
Await, Tagged] :
TemplateHead
Expression [+In, ?Yield,
?Await]
TemplateSpans [?Yield,
?Await, ?Tagged]
TemplateSpans [Yield, Await,
Tagged] : TemplateTail
TemplateMiddleList [Yield,
Await, Tagged] :
TemplateMiddle
Expression [+In, ?Yield,
?Await]
TemplateMiddleList [?Yield,
?Await, ?Tagged]
TemplateMiddle
Expression [+In, ?Yield,
?Await]
13.2.8.2 静的意味論:TemplateStrings
構文指向操作
TemplateStrings は引数 raw (Boolean)を取り、String または undefined の
List
を返す。次の生成規則ごとに定義される:
TemplateLiteral
: NoSubstitutionTemplate
« TemplateString (NoSubstitutionTemplate ,
raw ) » を返す。
SubstitutionTemplate
:
TemplateHead
Expression
TemplateSpans
head を « TemplateString (TemplateHead ,
raw ) » とする。
tail を TemplateSpans の TemplateStrings (引数
raw )とする。
head と tail の list-concatenation
を返す。
TemplateSpans :
TemplateTail
« TemplateString (TemplateTail ,
raw ) » を返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
middle を TemplateMiddleList の TemplateStrings (引数
raw )とする。
tail を « TemplateString (TemplateTail ,
raw ) » とする。
middle と tail の list-concatenation
を返す。
TemplateMiddleList
:
TemplateMiddle
Expression
« TemplateString (TemplateMiddle ,
raw ) » を返す。
TemplateMiddleList
:
TemplateMiddleList
TemplateMiddle
Expression
front を TemplateMiddleList の TemplateStrings (引数
raw )とする。
last を « TemplateString (TemplateMiddle ,
raw ) » とする。
front と last の list-concatenation
を返す。
13.2.8.3 静的意味論:TemplateString (
templateToken , raw )
抽象操作 TemplateString は、引数 templateToken (NoSubstitutionTemplate 構文ノード 、TemplateHead 構文ノード 、TemplateMiddle 構文ノード 、またはTemplateTail 構文ノード ) と
raw (Boolean)を取り、String または undefined を返す。呼び出されたとき、以下の手順を実行する:
raw が true の場合、
string を templateToken の TRV
とする。
そうでなければ、
string を templateToken の TV とする。
string を返す。
注
この操作は、raw が false かつ templateToken が NotEscapeSequence
を含んでいる場合は undefined を返す。それ以外の場合は String を返す。
13.2.8.4 GetTemplateObject ( templateLiteral )
抽象操作 GetTemplateObject は、引数 templateLiteral (構文ノード )を取り、配列を返す。呼び出されたとき、以下の手順を実行する:
realm を 現在の Realm Record とする。
templateRegistry を realm .[[TemplateMap]] とする。
templateRegistry の各要素 e について、
e .[[Site]] が templateLiteral
と 同じ構文ノード であれば、
e .[[Array]] を返す。
rawStrings を templateLiteral の TemplateStrings (引数
true )とする。
Assert :
rawStrings は String の List である。
cookedStrings を templateLiteral の TemplateStrings (引数
false )とする。
count を cookedStrings の List の要素数とする。
Assert :
count ≤ 232 - 1.
template を ! ArrayCreate (count ) とする。
rawObj を ! ArrayCreate (count ) とする。
index を 0 とする。
index < count の間、繰り返す:
prop を ! ToString (𝔽 (index )) とする。
cookedValue を cookedStrings [index ] とする。
! DefinePropertyOrThrow (template ,
prop , PropertyDescriptor { [[Value]] :
cookedValue , [[Writable]] :
false , [[Enumerable]] :
true , [[Configurable]] :
false }) を実行する。
rawValue を rawStrings [index ] の String 値とする。
! DefinePropertyOrThrow (rawObj ,
prop , PropertyDescriptor { [[Value]] :
rawValue , [[Writable]] :
false , [[Enumerable]] :
true , [[Configurable]] :
false }) を実行する。
index を index + 1 に設定する。
! SetIntegrityLevel (rawObj ,
frozen ) を実行する。
! DefinePropertyOrThrow (template ,
"raw" , PropertyDescriptor { [[Value]] :
rawObj , [[Writable]] : false ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
! SetIntegrityLevel (template ,
frozen ) を実行する。
realm .[[TemplateMap]] に Record { [[Site]] : templateLiteral , [[Array]] : template } を追加する。
template を返す。
注1
テンプレートオブジェクトの生成で 急激な完了
になることはない。
注2
realm
のプログラムコード内の各 TemplateLiteral
は、タグ付きテンプレートの評価(13.2.8.6 )で使用される一意のテンプレートオブジェクトと対応する。テンプレートオブジェクトはフリーズされ、特定のタグ付きテンプレートが評価されるたびに同じテンプレートオブジェクトが使用される。テンプレートオブジェクトが
TemplateLiteral
の初回評価時に遅延生成されるか、事前に生成されるかは実装依存であり、ECMAScript コードから観測できない。
注3
この仕様の将来の版で、テンプレートオブジェクトの追加の列挙不可プロパティが定義される可能性がある。
13.2.8.5 実行時意味論:SubstitutionEvaluation
構文指向操作
SubstitutionEvaluation は引数を取らず、ECMAScript 言語値 の
List を含む 通常完了 または 急激な完了
を返す。次の生成規則ごとに定義される:
TemplateSpans :
TemplateTail
新しい空の List を返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
? SubstitutionEvaluation の TemplateMiddleList を返す。
TemplateMiddleList
:
TemplateMiddle
Expression
subRef を ? Evaluation の
Expression
による評価結果とする。
sub を ? GetValue (subRef ) とする。
« sub » を返す。
TemplateMiddleList
:
TemplateMiddleList
TemplateMiddle
Expression
preceding を ? SubstitutionEvaluation の TemplateMiddleList を返す。
nextRef を ? Evaluation の
Expression
による評価結果とする。
next を ? GetValue (nextRef ) とする。
preceding と « next » の list-concatenation を返す。
13.2.8.6 実行時意味論:評価
TemplateLiteral
: NoSubstitutionTemplate
NoSubstitutionTemplate の
TV を 12.9.6
で定義された通りに返す。
SubstitutionTemplate
:
TemplateHead
Expression
TemplateSpans
head を TemplateHead の TV とし、12.9.6
で定義された通りとする。
subRef を ? Evaluation の
Expression
による評価結果とする。
sub を ? GetValue (subRef ) とする。
middle を ? ToString (sub ) とする。
tail を ? Evaluation の
TemplateSpans
とする。
head 、middle 、tail の string-concatenation を返す。
注1
Expression
の値に適用される文字列変換の意味論は String.prototype.concat のようなものであり、+
演算子とは異なる。
TemplateSpans :
TemplateTail
TemplateTail の
TV を 12.9.6
で定義された通りに返す。
TemplateSpans :
TemplateMiddleList
TemplateTail
head を ? Evaluation の
TemplateMiddleList とする。
tail を TemplateTail の TV とし、12.9.6
で定義された通りとする。
head と tail の string-concatenation を返す。
TemplateMiddleList
:
TemplateMiddle
Expression
head を TemplateMiddle の TV
とし、12.9.6
で定義された通りとする。
subRef を ? Evaluation の
Expression
による評価結果とする。
sub を ? GetValue (subRef ) とする。
middle を ? ToString (sub ) とする。
head と middle の string-concatenation を返す。
注2
Expression
の値に適用される文字列変換の意味論は String.prototype.concat のようなものであり、+
演算子とは異なる。
TemplateMiddleList
:
TemplateMiddleList
TemplateMiddle
Expression
rest を、TemplateMiddleList の
? Evaluation とする。
middle を、TemplateMiddle の TV (12.9.6
で定義)とする。
subRef を、Expression の ? Evaluation とする。
sub を、GetValue (subRef ) の
? 結果とする。
last を、ToString (sub ) の ? 結果とする。
rest 、middle 、last の string-concatenation を返す。
注3
Expression
の値に適用される文字列変換の意味論は、+ 演算子ではなく String.prototype.concat
に類似している。
13.2.9 グルーピング演算子
13.2.9.1 静的意味論:早期エラー
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
13.2.9.2 実行時意味論:評価
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
expr を、CoverParenthesizedExpressionAndArrowParameterList
によって カバーされている
ParenthesizedExpression
とする。
? Evaluation of expr を返す。
ParenthesizedExpression
:
(
Expression
)
Expression の
? Evaluation を返す。これが Reference 型の場合もある。
注
このアルゴリズムは、Expression
の Evaluation に対して
GetValue
を適用しない。主な理由は、delete や typeof などの演算子が括弧付き式に適用できるようにするためである。
13.3 左辺式(Left-Hand-Side Expressions)
構文
MemberExpression [Yield,
Await] :
PrimaryExpression [?Yield,
?Await]
MemberExpression [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
MemberExpression [?Yield,
?Await]
.
IdentifierName
MemberExpression [?Yield,
?Await]
TemplateLiteral [?Yield,
?Await, +Tagged]
SuperProperty [?Yield,
?Await]
MetaProperty
new
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
MemberExpression [?Yield,
?Await]
.
PrivateIdentifier
SuperProperty [Yield,
Await] :
super
[
Expression [+In, ?Yield,
?Await]
]
super
.
IdentifierName
MetaProperty :
NewTarget
ImportMeta
NewTarget :
new
.
target
ImportMeta :
import
.
meta
NewExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
new
NewExpression [?Yield,
?Await]
CallExpression [Yield,
Await] :
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
SuperCall [?Yield,
?Await]
ImportCall [?Yield,
?Await]
CallExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
CallExpression [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
CallExpression [?Yield,
?Await]
.
IdentifierName
CallExpression [?Yield,
?Await]
TemplateLiteral [?Yield,
?Await, +Tagged]
CallExpression [?Yield,
?Await]
.
PrivateIdentifier
SuperCall [Yield,
Await] :
super
Arguments [?Yield,
?Await]
ImportCall [Yield,
Await] :
import
(
AssignmentExpression [+In,
?Yield, ?Await]
,opt
)
import
(
AssignmentExpression [+In,
?Yield, ?Await]
,
AssignmentExpression [+In,
?Yield, ?Await]
,opt
)
Arguments [Yield,
Await] :
(
)
(
ArgumentList [?Yield,
?Await]
)
(
ArgumentList [?Yield,
?Await]
,
)
ArgumentList [Yield,
Await] :
AssignmentExpression [+In,
?Yield, ?Await]
...
AssignmentExpression [+In,
?Yield, ?Await]
ArgumentList [?Yield,
?Await]
,
AssignmentExpression [+In,
?Yield, ?Await]
ArgumentList [?Yield,
?Await]
,
...
AssignmentExpression [+In,
?Yield, ?Await]
OptionalExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
CallExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
OptionalExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
OptionalChain [Yield,
Await] :
?.
Arguments [?Yield,
?Await]
?.
[
Expression [+In, ?Yield,
?Await]
]
?.
IdentifierName
?.
TemplateLiteral [?Yield,
?Await, +Tagged]
?.
PrivateIdentifier
OptionalChain [?Yield,
?Await]
Arguments [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
OptionalChain [?Yield,
?Await]
.
IdentifierName
OptionalChain [?Yield,
?Await]
TemplateLiteral [?Yield,
?Await, +Tagged]
OptionalChain [?Yield,
?Await]
.
PrivateIdentifier
LeftHandSideExpression [Yield,
Await] :
NewExpression [?Yield,
?Await]
CallExpression [?Yield,
?Await]
OptionalExpression [?Yield,
?Await]
補助構文
次の生成規則のインスタンスを処理する際、
CallExpression :
CoverCallExpressionAndAsyncArrowHead
CoverCallExpressionAndAsyncArrowHead
の解釈は、次の文法を用いて詳細化される:
CallMemberExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
13.3.1 静的意味論
13.3.1.1 静的意味論:早期エラー
OptionalChain :
?.
TemplateLiteral
OptionalChain
TemplateLiteral
この生成規則に一致するソーステキストがある場合、構文エラーとなる。
注
この生成規則は、次のコードに対して自動セミコロン挿入規則(12.10 )が適用されるのを防ぐために存在する:
a?.b
`c`
このように2つの有効な文として解釈されるようにするためである。目的は、オプショナルチェーンなしの同様のコードとの一貫性を保つことである:
a.b
`c`
これは有効な文であり、自動セミコロン挿入は適用されない。
ImportMeta :
import
.
meta
13.3.2 プロパティアクセス
注
プロパティは名前でアクセスされ、ドット記法またはブラケット記法のいずれかを使う:
またはブラケット記法:
ドット記法は次の構文変換で説明できる:
これは次と同じ挙動となる:
同様に、
これは次と同じ挙動となる:
ここで <identifier-name-string > は IdentifierName の StringValue である。
13.3.2.1 実行時意味論:評価
MemberExpression
:
MemberExpression
[
Expression
]
baseReference を、MemberExpression の
? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
strict を IsStrict (この MemberExpression ) とする。
? EvaluatePropertyAccessWithExpressionKey (baseValue ,
Expression ,
strict ) を返す。
MemberExpression
:
MemberExpression
.
IdentifierName
baseReference を、MemberExpression の
? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
strict を IsStrict (この MemberExpression ) とする。
EvaluatePropertyAccessWithIdentifierKey (baseValue ,
IdentifierName ,
strict ) を返す。
MemberExpression
:
MemberExpression
.
PrivateIdentifier
baseReference を、MemberExpression の
? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
fieldNameString を PrivateIdentifier の StringValue とする。
MakePrivateReference (baseValue ,
fieldNameString ) を返す。
CallExpression :
CallExpression
[
Expression
]
baseReference を、CallExpression の ? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
strict を IsStrict (この CallExpression ) とする。
? EvaluatePropertyAccessWithExpressionKey (baseValue ,
Expression ,
strict ) を返す。
CallExpression :
CallExpression
.
IdentifierName
baseReference を、CallExpression の ? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
strict を IsStrict (この CallExpression ) とする。
EvaluatePropertyAccessWithIdentifierKey (baseValue ,
IdentifierName ,
strict ) を返す。
CallExpression :
CallExpression
.
PrivateIdentifier
baseReference を、CallExpression の ? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
fieldNameString を PrivateIdentifier の StringValue とする。
MakePrivateReference (baseValue ,
fieldNameString ) を返す。
13.3.3 EvaluatePropertyAccessWithExpressionKey (
baseValue , expression , strict )
抽象操作 EvaluatePropertyAccessWithExpressionKey は、引数 baseValue (ECMAScript
言語値 )、expression (Expression 構文ノード )、strict (Boolean)を取り、値を含む通常完了 または急激な完了
を返す。呼び出されたとき、以下の手順を実行する:
propertyNameReference を expression の ? Evaluation とする。
propertyNameValue を ? GetValue (propertyNameReference )
とする。
注:ほとんどの場合、propertyNameValue に ToPropertyKey
が直後に適用される。ただし a[b] = c の場合は c の評価後まで行われない。
Reference Record
{ [[Base]] : baseValue , [[ReferencedName]] : propertyNameValue , [[Strict]] : strict , [[ThisValue]] : empty } を返す。
13.3.4 EvaluatePropertyAccessWithIdentifierKey (
baseValue , identifierName , strict )
抽象操作 EvaluatePropertyAccessWithIdentifierKey は、引数 baseValue (ECMAScript
言語値 )、identifierName (IdentifierName 構文ノード )、strict (Boolean)を取り、Reference Record
を返す。呼び出されたとき、以下の手順を実行する:
propertyNameString を identifierName の StringValue とする。
Reference Record
{ [[Base]] : baseValue , [[ReferencedName]] : propertyNameString , [[Strict]] : strict , [[ThisValue]] : empty } を返す。
13.3.5 new 演算子
13.3.5.1 実行時意味論:評価
NewExpression :
new
NewExpression
? EvaluateNew (NewExpression ,
empty ) を返す。
MemberExpression
:
new
MemberExpression
Arguments
? EvaluateNew (MemberExpression , Arguments ) を返す。
13.3.5.1.1 EvaluateNew ( constructExpr ,
arguments )
抽象操作 EvaluateNew は、引数 constructExpr (NewExpression 構文ノード または MemberExpression
構文ノード )、arguments (empty
または
Arguments 構文ノード )を取り、値を含む通常完了 (ECMAScript 言語値 )または
急激な完了
を返す。呼び出されたとき、以下の手順を実行する:
ref を constructExpr の ? Evaluation とする。
constructor を ? GetValue (ref ) とする。
arguments が empty の場合、
argList を新しい空の List
とする。
それ以外の場合、
argList を arguments の ? ArgumentListEvaluation とする。
IsConstructor (constructor )
が false の場合、TypeError 例外をスローする。
? Construct (constructor ,
argList ) を返す。
13.3.6 関数呼び出し
13.3.6.1 実行時意味論:評価
CallExpression :
CoverCallExpressionAndAsyncArrowHead
expr を、CoverCallExpressionAndAsyncArrowHead
によって カバーされている
CallMemberExpression とする。
memberExpr を expr の MemberExpression とする。
arguments を expr の Arguments とする。
ref を memberExpr の ? Evaluation とする。
func を ? GetValue (ref ) とする。
ref が Reference
Record であり、IsPropertyReference (ref )
が false で、かつ ref .[[ReferencedName]] が "eval" の場合、
SameValue (func ,
%eval% ) が
true の場合、
argList を arguments の ? ArgumentListEvaluation
とする。
argList に要素がなければ undefined を返す。
evalArg を argList の最初の要素とする。
この CallExpression の
IsStrict が
true なら strictCaller を
true 、それ以外は false とする。
? PerformEval (evalArg ,
strictCaller , true ) を返す。
thisCall をこの CallExpression とする。
tailCall を IsInTailPosition (thisCall )
とする。
? EvaluateCall (func ,
ref , arguments , tailCall ) を返す。
CallExpression の評価で
6.a.v
のステップが実行された場合、それは 直接eval である。
CallExpression :
CallExpression
Arguments
ref を CallExpression の ? Evaluation とする。
func を ? GetValue (ref ) とする。
thisCall をこの CallExpression とする。
tailCall を IsInTailPosition (thisCall )
とする。
? EvaluateCall (func ,
ref , Arguments , tailCall ) を返す。
13.3.6.2 EvaluateCall ( func , ref ,
arguments , tailPosition )
抽象操作 EvaluateCall は、引数 func (ECMAScript 言語値 )、
ref (ECMAScript 言語値 または
Reference Record )、
arguments (構文ノード )、
tailPosition (Boolean)を取り、値を含む通常完了 (ECMAScript 言語値 )または 急激な完了
を返す。呼び出されたとき、以下の手順を実行する:
ref が Reference
Record の場合、
IsPropertyReference (ref )
が true の場合、
thisValue を GetThisValue (ref )
とする。
それ以外の場合、
refEnv を ref .[[Base]]
とする。
アサート : refEnv は
環境レコード である。
thisValue を refEnv .WithBaseObject() とする。
それ以外の場合、
thisValue を undefined とする。
argList を arguments の ? ArgumentListEvaluation とする。
func が オブジェクトでない
場合、TypeError 例外をスローする。
IsCallable (func ) が
false の場合、TypeError 例外をスローする。
tailPosition が true の場合、PrepareForTailCall () を実行する。
? Call (func ,
thisValue , argList ) を返す。
13.3.7 super キーワード
13.3.7.1 実行時意味論:評価
SuperProperty :
super
[
Expression
]
env を GetThisEnvironment () とする。
actualThis を ? env .GetThisBinding() とする。
propertyNameReference を Expression の ? Evaluation とする。
propertyNameValue を ? GetValue (propertyNameReference )
とする。
strict を IsStrict (この SuperProperty ) とする。
注:ほとんどの場合、propertyNameValue に ToPropertyKey
が直後に適用される。ただし super[b] = c の場合は c の評価後まで行われない。
MakeSuperPropertyReference (actualThis ,
propertyNameValue , strict ) を返す。
SuperProperty :
super
.
IdentifierName
env を GetThisEnvironment () とする。
actualThis を ? env .GetThisBinding() とする。
propertyKey を IdentifierName の StringValue とする。
strict を IsStrict (この SuperProperty ) とする。
MakeSuperPropertyReference (actualThis ,
propertyKey , strict ) を返す。
SuperCall :
super
Arguments
newTarget を GetNewTarget () とする。
アサート :
newTarget は コンストラクタ である。
func を GetSuperConstructor () とする。
argList を Arguments の ? ArgumentListEvaluation とする。
IsConstructor (func ) が
false の場合、TypeError 例外をスローする。
result を ? Construct (func ,
argList , newTarget ) とする。
thisER を GetThisEnvironment () とする。
アサート :
thisER は 関数環境レコード である。
? BindThisValue (thisER ,
result ) を実行する。
F を thisER .[[FunctionObject]] とする。
アサート :
F は ECMAScript の 関数オブジェクト である。
? InitializeInstanceElements (result ,
F ) を実行する。
result を返す。
13.3.7.2 GetSuperConstructor ( )
抽象操作 GetSuperConstructor は引数を取らず、ECMAScript 言語値
を返す。呼び出されたとき、以下の手順を実行する:
envRec を GetThisEnvironment () とする。
アサート :
envRec は 関数環境レコード である。
activeFunction を envRec .[[FunctionObject]] とする。
アサート :
activeFunction は ECMAScript の 関数オブジェクト である。
superConstructor を ! activeFunction .[[GetPrototypeOf]] () とする。
superConstructor を返す。
13.3.7.3 MakeSuperPropertyReference ( actualThis ,
propertyKey , strict )
抽象操作 MakeSuperPropertyReference は、引数 actualThis (ECMAScript 言語値 )、
propertyKey (ECMAScript 言語値 )、
strict (Boolean)を取り、Super Reference Record
を返す。呼び出されたとき、以下の手順を実行する:
env を GetThisEnvironment () とする。
アサート :
env .HasSuperBinding() は true である。
アサート :
env は 関数環境レコード である。
baseValue を GetSuperBase (env ) とする。
Reference
Record { [[Base]] :
baseValue , [[ReferencedName]] :
propertyKey , [[Strict]] : strict , [[ThisValue]] : actualThis }
を返す。
13.3.8 引数リスト
注
13.3.8.1 実行時意味論:ArgumentListEvaluation
構文指示操作
ArgumentListEvaluation は引数を取らず、値を含む通常完了 (リスト (ECMAScript 言語値 ))または急激な完了 を返す。以下の生成規則ごとに定義される:
Arguments :
(
)
新しい空のリスト を返す。
ArgumentList :
AssignmentExpression
ref を AssignmentExpression の
? Evaluation とする。
arg を ? GetValue (ref ) とする。
« arg » を返す。
ArgumentList :
...
AssignmentExpression
list を新しい空のリスト とする。
spreadRef を AssignmentExpression の
? Evaluation とする。
spreadObj を ? GetValue (spreadRef ) とする。
iteratorRecord を ? GetIterator (spreadObj ,
sync ) とする。
繰り返す:
next を ? IteratorStepValue (iteratorRecord )
とする。
next が done なら list を返す。
next を list に追加する。
ArgumentList :
ArgumentList
,
AssignmentExpression
precedingArgs を ArgumentList の ? ArgumentListEvaluation とする。
ref を AssignmentExpression の
? Evaluation とする。
arg を ? GetValue (ref ) とする。
precedingArgs と « arg » の list-concatenation
を返す。
ArgumentList :
ArgumentList
,
...
AssignmentExpression
precedingArgs を ArgumentList の ? ArgumentListEvaluation とする。
spreadRef を AssignmentExpression の
? Evaluation とする。
iteratorRecord を ? GetIterator (?
GetValue (spreadRef ),
sync ) とする。
繰り返す:
next を ? IteratorStepValue (iteratorRecord )
とする。
next が done なら precedingArgs
を返す。
next を precedingArgs に追加する。
TemplateLiteral
: NoSubstitutionTemplate
templateLiteral をこの TemplateLiteral とする。
siteObj を GetTemplateObject (templateLiteral )
とする。
« siteObj » を返す。
TemplateLiteral
: SubstitutionTemplate
templateLiteral をこの TemplateLiteral とする。
siteObj を GetTemplateObject (templateLiteral )
とする。
remaining を SubstitutionTemplate の
? ArgumentListEvaluation とする。
« siteObj » と remaining の list-concatenation
を返す。
SubstitutionTemplate
:
TemplateHead
Expression
TemplateSpans
firstSubRef を Expression の ? Evaluation とする。
firstSub を ? GetValue (firstSubRef ) とする。
restSub を TemplateSpans の ? SubstitutionEvaluation とする。
アサート :
restSub は空でもよいリスト である。
« firstSub » と restSub の list-concatenation
を返す。
13.3.9 オプショナルチェーン
注
オプショナルチェーンは、1つ以上のプロパティアクセスや関数呼び出しからなる連鎖で、その最初が ?.
トークンで始まる。
13.3.9.1 実行時意味論:評価
OptionalExpression
:
MemberExpression
OptionalChain
baseReference を MemberExpression の
? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
baseValue が undefined または null
のいずれかの場合、
undefined を返す。
OptionalChain の
? ChainEvaluation (引数 baseValue
および baseReference )を返す。
OptionalExpression
:
CallExpression
OptionalChain
baseReference を CallExpression の ? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
baseValue が undefined または null
のいずれかの場合、
undefined を返す。
OptionalChain の
? ChainEvaluation (引数 baseValue
および baseReference )を返す。
OptionalExpression
:
OptionalExpression
OptionalChain
baseReference を OptionalExpression の
? Evaluation とする。
baseValue を ? GetValue (baseReference ) とする。
baseValue が undefined または null
のいずれかの場合、
undefined を返す。
OptionalChain の
? ChainEvaluation (引数 baseValue
および baseReference )を返す。
13.3.9.2 実行時意味論:ChainEvaluation
構文指示操作
ChainEvaluation は引数 baseValue (ECMAScript
言語値 )、baseReference (ECMAScript 言語値 または Reference
Record )を取り、値を含む通常完了 (ECMAScript 言語値 または Reference
Record )または急激な完了 を返す。以下の生成規則ごとに定義される:
OptionalChain :
?.
Arguments
thisChain をこの OptionalChain とする。
tailCall を IsInTailPosition (thisChain )
とする。
? EvaluateCall (baseValue ,
baseReference , Arguments , tailCall ) を返す。
OptionalChain :
?.
[
Expression
]
strict を IsStrict (この OptionalChain ) とする。
? EvaluatePropertyAccessWithExpressionKey (baseValue ,
Expression ,
strict ) を返す。
OptionalChain :
?.
IdentifierName
strict を IsStrict (この OptionalChain ) とする。
EvaluatePropertyAccessWithIdentifierKey (baseValue ,
IdentifierName ,
strict ) を返す。
OptionalChain :
?.
PrivateIdentifier
fieldNameString を PrivateIdentifier の StringValue とする。
MakePrivateReference (baseValue ,
fieldNameString ) を返す。
OptionalChain :
OptionalChain
Arguments
optionalChain を OptionalChain とする。
newReference を optionalChain の ? ChainEvaluation (引数 baseValue
および baseReference )とする。
newValue を ? GetValue (newReference ) とする。
thisChain をこの OptionalChain とする。
tailCall を IsInTailPosition (thisChain )
とする。
? EvaluateCall (newValue ,
newReference , Arguments , tailCall ) を返す。
OptionalChain :
OptionalChain
[
Expression
]
optionalChain を OptionalChain とする。
newReference を optionalChain の ? ChainEvaluation (引数 baseValue
および baseReference )とする。
newValue を ? GetValue (newReference ) とする。
strict を IsStrict (この OptionalChain ) とする。
? EvaluatePropertyAccessWithExpressionKey (newValue ,
Expression ,
strict ) を返す。
OptionalChain :
OptionalChain
.
IdentifierName
optionalChain を OptionalChain とする。
newReference を optionalChain の ? ChainEvaluation (引数 baseValue
および baseReference )とする。
newValue を ? GetValue (newReference ) とする。
strict を IsStrict (この OptionalChain ) とする。
EvaluatePropertyAccessWithIdentifierKey (newValue ,
IdentifierName ,
strict ) を返す。
OptionalChain :
OptionalChain
.
PrivateIdentifier
optionalChain を OptionalChain とする。
newReference を optionalChain の ? ChainEvaluation (引数 baseValue
および baseReference )とする。
newValue を ? GetValue (newReference ) とする。
fieldNameString を PrivateIdentifier の StringValue とする。
MakePrivateReference (newValue ,
fieldNameString ) を返す。
13.3.10 import呼び出し
13.3.10.1 実行時意味論:評価
ImportCall :
import
(
AssignmentExpression
,opt
)
? EvaluateImportCall (AssignmentExpression )を返す。
ImportCall :
import
(
AssignmentExpression
,
AssignmentExpression
,opt
)
? EvaluateImportCall (最初の AssignmentExpression , 2番目の
AssignmentExpression )を返す。
13.3.10.2 EvaluateImportCall ( specifierExpression [
, optionsExpression ] )
抽象操作EvaluateImportCallは、引数specifierExpression (構文ノード )および省略可能な引数optionsExpression (構文ノード )を取り、値を含む通常完了 (Promise)または急激な完了 を返す。呼び出されたとき、次の手順を実行する:
referrer を GetActiveScriptOrModule ()
とする。
referrer が null なら、referrer に現在のRealm
Record を設定する。
specifierRef を specifierExpression の ? Evaluation とする。
specifier を ? GetValue (specifierRef ) とする。
optionsExpression が存在する場合、
optionsRef を optionsExpression の ? Evaluation とする。
options を ? GetValue (optionsRef )
とする。
それ以外の場合、
options を undefined とする。
promiseCapability を ! NewPromiseCapability (%Promise% ) とする。
specifierString を Completion (ToString (specifier )) とする。
IfAbruptRejectPromise (specifierString ,
promiseCapability ) を実行する。
attributes を新しい空のリスト とする。
options が undefined でない場合、
options がオブジェクトでない 場合、
! Call (promiseCapability .[[Reject]] , undefined , «
新しく作成されたTypeError オブジェクト ») を実行。
promiseCapability .[[Promise]]
を返す。
attributesObj を Completion (Get (options ,
"with" )) とする。
IfAbruptRejectPromise (attributesObj ,
promiseCapability ) を実行する。
attributesObj が undefined でない場合、
attributesObj がオブジェクトでない 場合、
! Call (promiseCapability .[[Reject]] ,
undefined , «
新しく作成されたTypeError オブジェクト ») を実行。
promiseCapability .[[Promise]] を返す。
entries を Completion (EnumerableOwnProperties (attributesObj ,
key+value )) とする。
IfAbruptRejectPromise (entries ,
promiseCapability ) を実行する。
entries の各要素 entry について、
key を ! Get (entry ,
"0" ) とする。
value を ! Get (entry ,
"1" ) とする。
key が String型 の場合、
value が String型でない 場合、
! Call (promiseCapability .[[Reject]] ,
undefined , «
新しく作成されたTypeError オブジェクト »)
を実行。
promiseCapability .[[Promise]] を返す。
ImportAttribute
Record { [[Key]] : key ,
[[Value]] :
value } を attributes
に追加する。
AllImportAttributesSupported (attributes )
が false の場合、
! Call (promiseCapability .[[Reject]] , undefined , «
新しく作成されたTypeError オブジェクト ») を実行。
promiseCapability .[[Promise]]
を返す。
attributes を、その各要素の[[Key]] フィールドをUTF-16コード単位列として扱い、辞書式順序でソートする。注:このソートは、ホスト が属性の列挙順に基づいて動作を変えるのを禁止することだけが観測可能である。
moduleRequest を新しいModuleRequest
Record { [[Specifier]] :
specifierString , [[Attributes]] :
attributes } とする。
HostLoadImportedModule (referrer ,
moduleRequest , empty ,
promiseCapability ) を実行する。
promiseCapability .[[Promise]] を返す。
13.3.10.3 ContinueDynamicImport ( promiseCapability ,
moduleCompletion )
抽象操作ContinueDynamicImportは、引数promiseCapability (PromiseCapability
Record )、moduleCompletion (値を含む通常完了 (Module Record )またはthrow
completion )を取り、unused を返す。この操作は、もともとimport() 呼び出しによって開始された動的importのプロセスを完了し、適切に約束をresolveまたはrejectする。呼び出されたとき、次の手順を実行する:
moduleCompletion が 急激な完了 の場合、
! Call (promiseCapability .[[Reject]] , undefined , «
moduleCompletion .[[Value]] »)
を実行する。
unused を返す。
module を moduleCompletion .[[Value]]
とする。
loadPromise を module .LoadRequestedModules() とする。
rejectedClosure
を、パラメータ(reason )を持ちpromiseCapability をキャプチャし、呼び出し時に以下を行う新しい抽象クロージャ とする:
! Call (promiseCapability .[[Reject]] , undefined , «
reason ») を実行する。
NormalCompletion (undefined )
を返す。
onRejected を CreateBuiltinFunction (rejectedClosure ,
1, "" , « ») とする。
linkAndEvaluateClosure
を、パラメータなしでmodule 、promiseCapability 、onRejected をキャプチャし、呼び出し時に以下を行う新しい抽象クロージャ とする:
link を Completion (module .Link())
とする。
link が 急激な完了
の場合、
! Call (promiseCapability .[[Reject]] , undefined , «
link .[[Value]] ») を実行する。
NormalCompletion (undefined )
を返す。
evaluatePromise を module .Evaluate() とする。
fulfilledClosure
を、パラメータなしでmodule とpromiseCapability をキャプチャし、呼び出し時に以下を行う新しい抽象クロージャ とする:
namespace を GetModuleNamespace (module )
とする。
! Call (promiseCapability .[[Resolve]] , undefined , «
namespace ») を実行する。
NormalCompletion (undefined )
を返す。
onFulfilled を CreateBuiltinFunction (fulfilledClosure ,
0, "" , « ») とする。
PerformPromiseThen (evaluatePromise ,
onFulfilled , onRejected ) を実行する。
unused を返す。
linkAndEvaluate を CreateBuiltinFunction (linkAndEvaluateClosure ,
0, "" , « ») とする。
PerformPromiseThen (loadPromise ,
linkAndEvaluate , onRejected ) を実行する。
unused を返す。
13.3.11 タグ付きテンプレート
注
タグ付きテンプレートは、呼び出しの引数がTemplateLiteral
(13.2.8 )から導出される関数呼び出しである。実際の引数は、テンプレートオブジェクト(13.2.8.4 )およびTemplateLiteral 内に埋め込まれた式を評価して得られる値を含む。
13.3.11.1 実行時意味論:評価
MemberExpression
:
MemberExpression
TemplateLiteral
tagRef を MemberExpression の
? Evaluation とする。
tagFunc を ? GetValue (tagRef ) とする。
thisCall をこの MemberExpression とする。
tailCall を IsInTailPosition (thisCall )
とする。
? EvaluateCall (tagFunc ,
tagRef , TemplateLiteral ,
tailCall ) を返す。
CallExpression :
CallExpression
TemplateLiteral
tagRef を CallExpression の ? Evaluation とする。
tagFunc を ? GetValue (tagRef ) とする。
thisCall をこの CallExpression とする。
tailCall を IsInTailPosition (thisCall )
とする。
? EvaluateCall (tagFunc ,
tagRef , TemplateLiteral ,
tailCall ) を返す。
13.3.12 メタプロパティ
13.3.12.1 実行時意味論:評価
NewTarget :
new
.
target
GetNewTarget () を返す。
ImportMeta :
import
.
meta
module を GetActiveScriptOrModule ()
とする。
アサート :
module は Source Text Module Record である。
importMeta を module .[[ImportMeta]]
とする。
importMeta が empty の場合、
importMeta に OrdinaryObjectCreate (null )
を設定する。
importMetaValues を HostGetImportMetaProperties (module )
とする。
importMetaValues の各 Record
{ [[Key]] , [[Value]] } p について、
! CreateDataPropertyOrThrow (importMeta ,
p .[[Key]] , p .[[Value]] ) を実行する。
HostFinalizeImportMeta (importMeta ,
module ) を実行する。
module .[[ImportMeta]] に
importMeta を設定する。
importMeta を返す。
それ以外の場合、
アサート : importMeta
はオブジェクトである 。
importMeta を返す。
13.3.12.1.1 HostGetImportMetaProperties (
moduleRecord )
ホスト定義 の抽象操作HostGetImportMetaPropertiesは、引数moduleRecord (Module Record )を取り、リスト (フィールド[[Key]] (プロパティキー )と[[Value]] (ECMAScript
言語値 )を持つRecord )を返す。これにより、ホスト はimport.metaから返されるオブジェクトに対してプロパティキー と値を提供できる。
HostGetImportMetaPropertiesのデフォルト実装は、新しい空のリスト を返すことである。
13.3.12.1.2 HostFinalizeImportMeta ( importMeta ,
moduleRecord )
ホスト定義 の抽象操作HostFinalizeImportMetaは、引数importMeta (オブジェクト)およびmoduleRecord (Module
Record )を取り、unused を返す。これにより、ホスト はimport.metaから返されるオブジェクトをECMAScriptコードに公開する前に特別な操作を行うことができる。
ほとんどのホスト は、HostGetImportMetaProperties を定義し、HostFinalizeImportMetaはデフォルトの挙動のままでよい。しかし、HostFinalizeImportMetaは、ホスト がオブジェクトを直接操作する必要がある場合のための「エスケープハッチ」を提供する。
HostFinalizeImportMetaのデフォルト実装はunused を返すことである。
13.4 更新式
構文
UpdateExpression [Yield,
Await] :
LeftHandSideExpression [?Yield,
?Await]
LeftHandSideExpression [?Yield,
?Await]
[ここに LineTerminator はない]
++
LeftHandSideExpression [?Yield,
?Await]
[ここに LineTerminator はない]
--
++
UnaryExpression [?Yield,
?Await]
--
UnaryExpression [?Yield,
?Await]
13.4.1 静的意味論:早期エラー
UpdateExpression :
LeftHandSideExpression
++
LeftHandSideExpression
--
UpdateExpression :
++
UnaryExpression
--
UnaryExpression
13.4.2 後置インクリメント演算子
13.4.2.1 実行時意味論:評価
UpdateExpression
:
LeftHandSideExpression
++
lhs を LeftHandSideExpression の
? Evaluation とする。
LeftHandSideExpression の
AssignmentTargetType
が web-compat の場合、ReferenceError 例外をスローする。
oldValue を ? ToNumeric (?
GetValue (lhs )) とする。
oldValue が Number の場合、
newValue を Number::add (oldValue ,
1 𝔽 ) とする。
それ以外の場合、
アサート : oldValue は BigInt
である。
newValue を BigInt::add (oldValue ,
1 ℤ ) とする。
? PutValue (lhs ,
newValue ) を実行する。
oldValue を返す。
13.4.3 後置デクリメント演算子
13.4.3.1 実行時意味論:評価
UpdateExpression
:
LeftHandSideExpression
--
lhs を LeftHandSideExpression の
? Evaluation とする。
LeftHandSideExpression の
AssignmentTargetType
が web-compat の場合、ReferenceError 例外をスローする。
oldValue を ? ToNumeric (?
GetValue (lhs )) とする。
oldValue が Number の場合、
newValue を Number::subtract (oldValue ,
1 𝔽 ) とする。
それ以外の場合、
アサート : oldValue は BigInt
である。
newValue を BigInt::subtract (oldValue ,
1 ℤ ) とする。
? PutValue (lhs ,
newValue ) を実行する。
oldValue を返す。
13.4.4 前置インクリメント演算子
13.4.4.1 実行時意味論:評価
UpdateExpression
:
++
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
UnaryExpression
の AssignmentTargetType
が web-compat の場合、ReferenceError 例外をスローする。
oldValue を ? ToNumeric (?
GetValue (expr )) とする。
oldValue が Number の場合、
newValue を Number::add (oldValue ,
1 𝔽 ) とする。
それ以外の場合、
アサート : oldValue は BigInt
である。
newValue を BigInt::add (oldValue ,
1 ℤ ) とする。
? PutValue (expr ,
newValue ) を実行する。
newValue を返す。
13.4.5 前置デクリメント演算子
13.4.5.1 実行時意味論:評価
UpdateExpression
:
--
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
UnaryExpression
の AssignmentTargetType
が web-compat の場合、ReferenceError 例外をスローする。
oldValue を ? ToNumeric (?
GetValue (expr )) とする。
oldValue が Number の場合、
newValue を Number::subtract (oldValue ,
1 𝔽 ) とする。
それ以外の場合、
アサート : oldValue は BigInt
である。
newValue を BigInt::subtract (oldValue ,
1 ℤ ) とする。
? PutValue (expr ,
newValue ) を実行する。
newValue を返す。
13.5 単項演算子
構文
UnaryExpression [Yield,
Await] :
UpdateExpression [?Yield,
?Await]
delete
UnaryExpression [?Yield,
?Await]
void
UnaryExpression [?Yield,
?Await]
typeof
UnaryExpression [?Yield,
?Await]
+
UnaryExpression [?Yield,
?Await]
-
UnaryExpression [?Yield,
?Await]
~
UnaryExpression [?Yield,
?Await]
!
UnaryExpression [?Yield,
?Await]
[+Await]
AwaitExpression [?Yield]
13.5.1 delete 演算子
13.5.1.1 静的意味論:早期エラー
UnaryExpression
:
delete
UnaryExpression
注
最後の規則は、delete (((foo))) のような式が、最初の規則を再帰的に適用することで早期エラー
となることを意味する。
13.5.1.2 実行時意味論:評価
UnaryExpression
:
delete
UnaryExpression
ref を UnaryExpression の ? Evaluation とする。
ref が Reference
Record でない場合、true を返す。
IsUnresolvableReference (ref )
が true の場合、
アサート : ref .[[Strict]] は false である。
true を返す。
IsPropertyReference (ref )
が true の場合、
アサート : IsPrivateReference (ref )
は false である。
IsSuperReference (ref )
が true の場合、ReferenceError 例外をスローする。
baseObj を
ref .[[Base]] の ? ToObject とする。
ref .[[ReferencedName]] が property
key でない場合、
ref .[[ReferencedName]] に
? ToPropertyKey (ref .[[ReferencedName]] ) を設定する。
deleteStatus を ? baseObj .[[Delete]] (ref .[[ReferencedName]] ) とする。
deleteStatus が false かつ
ref .[[Strict]] が
true の場合、TypeError 例外をスローする。
deleteStatus を返す。
それ以外の場合、
base を ref .[[Base]] とする。
アサート : base は
Environment Record
である。
base .DeleteBinding (ref .[[ReferencedName]] ) を返す。
注1
delete 演算子が strict mode code 内に出現する場合、その
UnaryExpression
が変数、関数引数、または関数名への直接参照である場合、SyntaxError 例外がスローされる。さらに、strict mode code 内で
delete 演算子が削除対象のプロパティが { [[Configurable]] :
false } の属性(またはその他削除できない場合)であるとき、TypeError
例外がスローされる。
注2
4.c
で作成される可能性のあるオブジェクトは、上記の抽象操作および ordinary object の [[Delete]]
内部メソッドの外部からはアクセスできない。実装によっては、そのオブジェクトの実際の生成を回避してもよい。
13.5.2 void 演算子
13.5.2.1 実行時意味論:評価
UnaryExpression
:
void
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
? GetValue (expr ) を実行する。
undefined を返す。
注
GetValue
は、その値が利用されなくても観測可能な副作用があるかもしれないので必ず呼び出される。
13.5.3 typeof 演算子
13.5.3.1 実行時意味論:評価
UnaryExpression
:
typeof
UnaryExpression
val を UnaryExpression の ? Evaluation とする。
val が Reference
Record の場合、
IsUnresolvableReference (val )
が true なら "undefined" を返す。
val を ? GetValue (val ) に設定する。
val が undefined なら
"undefined" を返す。
val が null なら "object" を返す。
val が String
の場合、"string" を返す。
val が Symbol
の場合、"symbol" を返す。
val が Boolean
の場合、"boolean" を返す。
val が Number
の場合、"number" を返す。
val が BigInt
の場合、"bigint" を返す。
アサート :
val は オブジェクトである 。
注:このステップは B.3.6.3 で置き換えられる。
val が [[Call]]
内部メソッドを持つ場合、"function" を返す。
"object" を返す。
13.5.4 単項 + 演算子
注
単項+演算子は、そのオペランドをNumber型 に変換する。
13.5.4.1 実行時意味論:評価
UnaryExpression
:
+
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
? ToNumber (? GetValue (expr )) を返す。
13.5.5 単項 - 演算子
注
単項 - 演算子は、そのオペランドを数値に変換し、次にそれを符号反転する。+0 𝔽
の符号反転は -0 𝔽 となり、-0 𝔽 の符号反転は
+0 𝔽 となる。
13.5.5.1 実行時意味論:評価
UnaryExpression
:
-
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
oldValue を ? ToNumeric (?
GetValue (expr )) とする。
oldValue が Number の場合、
Number::unaryMinus (oldValue )
を返す。
それ以外の場合、
アサート : oldValue は BigInt
である。
BigInt::unaryMinus (oldValue )
を返す。
13.5.6 ビット単位否定演算子 ( ~ )
13.5.6.1 実行時意味論:評価
UnaryExpression
:
~
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
oldValue を ? ToNumeric (?
GetValue (expr )) とする。
oldValue が Number の場合、
Number::bitwiseNOT (oldValue )
を返す。
それ以外の場合、
アサート : oldValue は BigInt
である。
BigInt::bitwiseNOT (oldValue )
を返す。
13.5.7 論理否定演算子 ( ! )
13.5.7.1 実行時意味論:評価
UnaryExpression
:
!
UnaryExpression
expr を UnaryExpression の ? Evaluation とする。
oldValue を ToBoolean (? GetValue (expr )) とする。
oldValue が true なら false を返す。
true を返す。
13.6 累乗演算子
構文
ExponentiationExpression [Yield,
Await] :
UnaryExpression [?Yield,
?Await]
UpdateExpression [?Yield,
?Await]
**
ExponentiationExpression [?Yield,
?Await]
13.6.1 実行時意味論:評価
ExponentiationExpression
:
UpdateExpression
**
ExponentiationExpression
? EvaluateStringOrNumericBinaryExpression (UpdateExpression ,
**, ExponentiationExpression )
を返す。
13.7 乗除演算子
構文
MultiplicativeExpression [Yield,
Await] :
ExponentiationExpression [?Yield,
?Await]
MultiplicativeExpression [?Yield,
?Await]
MultiplicativeOperator
ExponentiationExpression [?Yield,
?Await]
MultiplicativeOperator
: one of * /
%
注
* 演算子は乗算を行い、被演算子の積を生成する。
/ 演算子は除算を行い、被演算子の商を生成する。
% 演算子は、暗黙の除算から被演算子の剰余を返す。
13.7.1 実行時意味論:評価
MultiplicativeExpression
:
MultiplicativeExpression
MultiplicativeOperator
ExponentiationExpression
opText を source text matched
by MultiplicativeOperator とする。
? EvaluateStringOrNumericBinaryExpression (MultiplicativeExpression ,
opText , ExponentiationExpression )
を返す。
13.8 加算演算子
構文
AdditiveExpression [Yield,
Await] :
MultiplicativeExpression [?Yield,
?Await]
AdditiveExpression [?Yield,
?Await]
+
MultiplicativeExpression [?Yield,
?Await]
AdditiveExpression [?Yield,
?Await]
-
MultiplicativeExpression [?Yield,
?Await]
13.8.1 加算演算子 ( + )
注
加算演算子は、文字列連結または数値加算のいずれかを実行する。
13.8.1.1 実行時意味論:評価
AdditiveExpression
:
AdditiveExpression
+
MultiplicativeExpression
? EvaluateStringOrNumericBinaryExpression (AdditiveExpression ,
+, MultiplicativeExpression )
を返す。
13.8.2 減算演算子 ( - )
注
13.8.2.1 実行時意味論:評価
AdditiveExpression
:
AdditiveExpression
-
MultiplicativeExpression
? EvaluateStringOrNumericBinaryExpression (AdditiveExpression ,
-, MultiplicativeExpression )
を返す。
13.9 ビットシフト演算子
構文
ShiftExpression [Yield,
Await] :
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
<<
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
>>
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
>>>
AdditiveExpression [?Yield,
?Await]
13.9.1 左シフト演算子 ( << )
注
左オペランドのビットを、右オペランドで指定された分だけ左にシフトするビット単位の左シフト演算を行う。
13.9.1.1 実行時意味論:評価
ShiftExpression
:
ShiftExpression
<<
AdditiveExpression
? EvaluateStringOrNumericBinaryExpression (ShiftExpression ,
<<, AdditiveExpression ) を返す。
13.9.2 符号付き右シフト演算子 ( >> )
注
左オペランドのビットを、右オペランドで指定された分だけ符号ビットを保持したまま右にシフトするビット単位の右シフト演算を行う。
13.9.2.1 実行時意味論:評価
ShiftExpression
:
ShiftExpression
>>
AdditiveExpression
? EvaluateStringOrNumericBinaryExpression (ShiftExpression ,
>>, AdditiveExpression ) を返す。
13.9.3 符号なし右シフト演算子 ( >>>
)
注
左オペランドのビットを、右オペランドで指定された分だけゼロ埋めで右にシフトするビット単位の右シフト演算を行う。
13.9.3.1 実行時意味論:評価
ShiftExpression
:
ShiftExpression
>>>
AdditiveExpression
? EvaluateStringOrNumericBinaryExpression (ShiftExpression ,
>>>, AdditiveExpression ) を返す。
13.10 関係演算子
注1
関係演算子の評価結果は常にBoolean型であり、演算子が示す関係が2つのオペランド間で成り立つかどうかを反映する。
構文
RelationalExpression [In,
Yield, Await] :
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
<
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
>
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
<=
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
>=
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
instanceof
ShiftExpression [?Yield,
?Await]
[+In]
RelationalExpression [+In,
?Yield, ?Await]
in
ShiftExpression [?Yield,
?Await]
[+In]
PrivateIdentifier
in
ShiftExpression [?Yield,
?Await]
注2
[In] 文法パラメータは、関係式の in 演算子と for 文中の in
演算子との混同を避けるために必要である。
13.10.1 実行時意味論:評価
RelationalExpression
:
RelationalExpression
<
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を ? IsLessThan (lVal , rVal ,
true ) とする。
r が undefined なら false を返し、それ以外は
r を返す。
RelationalExpression
:
RelationalExpression
>
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を ? IsLessThan (rVal , lVal ,
false ) とする。
r が undefined なら false を返し、それ以外は
r を返す。
RelationalExpression
:
RelationalExpression
<=
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を ? IsLessThan (rVal , lVal ,
false ) とする。
r が true または undefined なら
false を返し、それ以外は true を返す。
RelationalExpression
:
RelationalExpression
>=
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を ? IsLessThan (lVal , rVal ,
true ) とする。
r が true または undefined なら
false を返し、それ以外は true を返す。
RelationalExpression
:
RelationalExpression
instanceof
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? InstanceofOperator (lVal ,
rVal ) を返す。
RelationalExpression
:
RelationalExpression
in
ShiftExpression
lRef を RelationalExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
rVal が オブジェクトでない 場合、TypeError
例外をスローする。
? HasProperty (rVal , ? ToPropertyKey (lVal )) を返す。
RelationalExpression
:
PrivateIdentifier
in
ShiftExpression
privateIdentifier を PrivateIdentifier の StringValue とする。
rRef を ShiftExpression の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
rVal が オブジェクトでない 場合、TypeError
例外をスローする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
アサート :
privateEnv は null でない。
privateName を ResolvePrivateIdentifier (privateEnv ,
privateIdentifier ) とする。
PrivateElementFind (rVal ,
privateName ) が empty でない場合、true
を返す。
false を返す。
13.10.2 InstanceofOperator ( V , target )
抽象操作 InstanceofOperator は、引数 V (ECMAScript
言語値 )、target (ECMAScript
言語値 )を取り、Booleanを含む通常完了 またはthrow completion を返す。これは
target の %Symbol.hasInstance% メソッドを参照するか、存在しない場合は
target の "prototype" プロパティの値が V
のプロトタイプチェーンに存在するかを判定することで、V が target
のインスタンスかどうかを判定する一般的なアルゴリズムを実装する。呼び出されたとき、次の手順を実行する:
target が オブジェクトでない 場合、TypeError
例外をスローする。
instOfHandler を ? GetMethod (target , %Symbol.hasInstance% ) とする。
instOfHandler が undefined でない場合、
ToBoolean (? Call (instOfHandler ,
target , « V »)) を返す。
IsCallable (target ) が
false の場合、TypeError 例外をスローする。
? OrdinaryHasInstance (target ,
V ) を返す。
注
4 および 5 のステップは、%Symbol.hasInstance% メソッドを使って
instanceof 演算子の意味論を定義していなかった以前のECMAScript版との互換性のために提供されている。オブジェクトが
%Symbol.hasInstance%
を定義または継承していない場合、デフォルトの instanceof 意味論が使われる。
13.11 等価演算子
注
等価演算子の評価結果は常にBoolean型であり、演算子が示す関係が2つのオペランド間で成り立つかどうかを反映する。
構文
EqualityExpression [In, Yield,
Await] :
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
==
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
!=
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
===
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
!==
RelationalExpression [?In,
?Yield, ?Await]
13.11.1 実行時意味論:評価
EqualityExpression
:
EqualityExpression
==
RelationalExpression
lRef を EqualityExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を RelationalExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? IsLooselyEqual (rVal ,
lVal ) を返す。
EqualityExpression
:
EqualityExpression
!=
RelationalExpression
lRef を EqualityExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を RelationalExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を ? IsLooselyEqual (rVal ,
lVal ) とする。
r が true なら false を返し、それ以外は
true を返す。
EqualityExpression
:
EqualityExpression
===
RelationalExpression
lRef を EqualityExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を RelationalExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
IsStrictlyEqual (rVal ,
lVal ) を返す。
EqualityExpression
:
EqualityExpression
!==
RelationalExpression
lRef を EqualityExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を RelationalExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
r を IsStrictlyEqual (rVal ,
lVal ) とする。
r が true なら false を返し、それ以外は
true を返す。
注1
上記の等価の定義に基づく:
文字列比較を強制するには: `${a}` == `${b}`
数値比較を強制するには: +a == +b
真偽値比較を強制するには: !a == !b
注2
等価演算子は以下の不変性を維持する:
A != B は !(A == B) と同値である。
A == B は B == A
と同値であるが、AとBの評価順は異なる。
注3
等価演算子は常に推移的であるとは限りません。例えば、同じ文字列値を表す2つの異なるStringオブジェクトが存在する場合、それぞれのStringオブジェクトは==演算子によってその文字列値と等しいと見なされますが、2つのStringオブジェクト同士は等しくありません。例:
new String("a") == "a" および "a" == new String("a") はどちらも
true です。
new String("a") == new String("a") は false です。
注4
文字列の比較は、コード単位値の並びに対する単純な等価テストを使用します。Unicode仕様で定義されているより複雑で意味論的な文字や文字列の等価性や照合順序の定義は使用されません。そのため、Unicode
Standardに従って正規等価なString値でも等しくないと判定される場合があります。実質的にこのアルゴリズムは、両方のStringがすでに正規化された形式であると仮定しています。
13.12 2項ビット単位演算子
構文
BitwiseANDExpression [In,
Yield, Await] :
EqualityExpression [?In,
?Yield, ?Await]
BitwiseANDExpression [?In,
?Yield, ?Await]
&
EqualityExpression [?In,
?Yield, ?Await]
BitwiseXORExpression [In,
Yield, Await] :
BitwiseANDExpression [?In,
?Yield, ?Await]
BitwiseXORExpression [?In,
?Yield, ?Await]
^
BitwiseANDExpression [?In,
?Yield, ?Await]
BitwiseORExpression [In,
Yield, Await] :
BitwiseXORExpression [?In,
?Yield, ?Await]
BitwiseORExpression [?In,
?Yield, ?Await]
|
BitwiseXORExpression [?In,
?Yield, ?Await]
13.12.1 実行時意味論:評価
BitwiseANDExpression
:
BitwiseANDExpression
&
EqualityExpression
? EvaluateStringOrNumericBinaryExpression (BitwiseANDExpression ,
&, EqualityExpression ) を返す。
BitwiseXORExpression
:
BitwiseXORExpression
^
BitwiseANDExpression
? EvaluateStringOrNumericBinaryExpression (BitwiseXORExpression ,
^, BitwiseANDExpression ) を返す。
BitwiseORExpression
:
BitwiseORExpression
|
BitwiseXORExpression
? EvaluateStringOrNumericBinaryExpression (BitwiseORExpression ,
|, BitwiseXORExpression ) を返す。
13.13 2項論理演算子
構文
LogicalANDExpression [In,
Yield, Await] :
BitwiseORExpression [?In,
?Yield, ?Await]
LogicalANDExpression [?In,
?Yield, ?Await]
&&
BitwiseORExpression [?In,
?Yield, ?Await]
LogicalORExpression [In,
Yield, Await] :
LogicalANDExpression [?In,
?Yield, ?Await]
LogicalORExpression [?In,
?Yield, ?Await]
||
LogicalANDExpression [?In,
?Yield, ?Await]
CoalesceExpression [In, Yield,
Await] :
CoalesceExpressionHead [?In,
?Yield, ?Await]
??
BitwiseORExpression [?In,
?Yield, ?Await]
CoalesceExpressionHead [In,
Yield, Await] :
CoalesceExpression [?In,
?Yield, ?Await]
BitwiseORExpression [?In,
?Yield, ?Await]
ShortCircuitExpression [In,
Yield, Await] :
LogicalORExpression [?In,
?Yield, ?Await]
CoalesceExpression [?In,
?Yield, ?Await]
注
&& または ||
演算子によって生成される値は、必ずしもBoolean型とは限りません。生成される値は常に2つのオペランド式のいずれかの値になります。
13.13.1 実行時意味論:評価
LogicalANDExpression
:
LogicalANDExpression
&&
BitwiseORExpression
lRef を LogicalANDExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
ToBoolean (lVal ) が
false の場合、lVal を返す。
rRef を BitwiseORExpression の
? Evaluation とする。
? GetValue (rRef ) を返す。
LogicalORExpression
:
LogicalORExpression
||
LogicalANDExpression
lRef を LogicalORExpression の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
ToBoolean (lVal ) が
true の場合、lVal を返す。
rRef を LogicalANDExpression の
? Evaluation とする。
? GetValue (rRef ) を返す。
CoalesceExpression
:
CoalesceExpressionHead
??
BitwiseORExpression
lRef を CoalesceExpressionHead の
? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
lVal が undefined または null の場合、
rRef を BitwiseORExpression の
? Evaluation とする。
? GetValue (rRef ) を返す。
それ以外の場合、
lVal を返す。
13.14 条件演算子 ( ? : )
構文
ConditionalExpression [In,
Yield, Await] :
ShortCircuitExpression [?In,
?Yield, ?Await]
ShortCircuitExpression [?In,
?Yield, ?Await]
?
AssignmentExpression [+In,
?Yield, ?Await]
:
AssignmentExpression [?In,
?Yield, ?Await]
注
ECMAScriptにおけるConditionalExpression の文法は、CやJavaとはわずかに異なります。CやJavaでは2番目の部分式にExpression を許可しつつ、3番目の式はConditionalExpression に制限されています。ECMAScriptでこのような違いがある理由は、条件式のいずれかの側で代入式が使えるようにし、中心式がコンマ式となる混乱しやすくあまり有用でないケースを排除するためです。
13.14.1 実行時意味論:評価
ConditionalExpression
:
ShortCircuitExpression
?
AssignmentExpression
:
AssignmentExpression
lRef を ShortCircuitExpression の
? Evaluation とする。
lVal を ToBoolean (? GetValue (lRef )) とする。
lVal が true の場合、
trueRef を 1番目の AssignmentExpression の
? Evaluation とする。
? GetValue (trueRef ) を返す。
それ以外の場合、
falseRef を 2番目の AssignmentExpression の
? Evaluation とする。
? GetValue (falseRef ) を返す。
13.15 代入演算子
構文
AssignmentExpression [In,
Yield, Await] :
ConditionalExpression [?In,
?Yield, ?Await]
[+Yield]
YieldExpression [?In,
?Await]
ArrowFunction [?In, ?Yield,
?Await]
AsyncArrowFunction [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
AssignmentOperator
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
&&=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
||=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
??=
AssignmentExpression [?In,
?Yield, ?Await]
AssignmentOperator :
one of *= /= %=
+= -= <<= >>=
>>>= &= ^= |=
**=
13.15.1 静的意味論:早期エラー
AssignmentExpression
:
LeftHandSideExpression
=
AssignmentExpression
AssignmentExpression
:
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
AssignmentExpression
:
LeftHandSideExpression
&&=
AssignmentExpression
LeftHandSideExpression
||=
AssignmentExpression
LeftHandSideExpression
??=
AssignmentExpression
13.15.2 実行時意味論:評価
AssignmentExpression
:
LeftHandSideExpression
=
AssignmentExpression
LeftHandSideExpression が
ObjectLiteral でも
ArrayLiteral でもない場合、
lRef を LeftHandSideExpression
の ? Evaluation とする。
LeftHandSideExpression
の AssignmentTargetType
が web-compat の場合、ReferenceError
例外をスローする。
IsAnonymousFunctionDefinition (AssignmentExpression ) が
true かつ IsIdentifierRef
of LeftHandSideExpression
が true である場合、
lhs を LeftHandSideExpression
の StringValue
とする。
rVal を AssignmentExpression
の NamedEvaluation (引数
lhs )の結果とする。
それ以外の場合、
rRef を AssignmentExpression
の ? Evaluation とする。
rVal を ? GetValue (rRef ).
? PutValue (lRef ,
rVal ) を実行する。
rVal を返す。
assignmentPattern を AssignmentPattern で、LeftHandSideExpression
にカバーされている ものとする。
rRef を AssignmentExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? DestructuringAssignmentEvaluation (assignmentPattern ,引数
rVal )を実行する。
rVal を返す。
AssignmentExpression
:
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
lRef を LeftHandSideExpression の
? Evaluation とする。
LeftHandSideExpression の
AssignmentTargetType
が web-compat の場合、ReferenceError 例外をスローする。
lVal を
? GetValue (lRef ) とする。
rRef を AssignmentExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
assignmentOpText を AssignmentOperator がマッチした ソーステキスト
とする。
opText を次の表において assignmentOpText に対応するUnicodeコードポイントの列とする:
assignmentOpText
opText
**=
**
*=
*
/=
/
%=
%
+=
+
-=
-
<<=
<<
>>=
>>
>>>=
>>>
&=
&
^=
^
|=
|
r を lVal , opText , rVal を引数として
? ApplyStringOrNumericBinaryOperator を呼ぶ。
? PutValue (lRef , r )
を実行する。
r を返す。
AssignmentExpression
:
LeftHandSideExpression
&&=
AssignmentExpression
lRef を LeftHandSideExpression の
? Evaluation とする。
lVal を
? GetValue (lRef ) とする。
ToBoolean (lVal ) が
false の場合、lVal を返す。
IsAnonymousFunctionDefinition (AssignmentExpression ) が
true かつ IsIdentifierRef of
LeftHandSideExpression が
true である場合、
lhs を LeftHandSideExpression
の StringValue とする。
rVal を AssignmentExpression の
NamedEvaluation (引数
lhs )の結果とする。
それ以外の場合、
rRef を AssignmentExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? PutValue (lRef , rVal )
を実行する。
rVal を返す。
AssignmentExpression
:
LeftHandSideExpression
||=
AssignmentExpression
lRef を LeftHandSideExpression の
? Evaluation とする。
lVal を
? GetValue (lRef ) とする。
ToBoolean (lVal ) が
true の場合、lVal を返す。
IsAnonymousFunctionDefinition (AssignmentExpression ) が
true かつ IsIdentifierRef of
LeftHandSideExpression が
true である場合、
lhs を LeftHandSideExpression
の StringValue とする。
rVal を AssignmentExpression の
NamedEvaluation (引数
lhs )の結果とする。
それ以外の場合、
rRef を AssignmentExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? PutValue (lRef , rVal )
を実行する。
rVal を返す。
AssignmentExpression
:
LeftHandSideExpression
??=
AssignmentExpression
lRef を LeftHandSideExpression の
? Evaluation とする。
lVal を
? GetValue (lRef ) とする。
lVal が undefined でも null
でもない場合、lVal を返す。
IsAnonymousFunctionDefinition (AssignmentExpression ) が
true かつ IsIdentifierRef of
LeftHandSideExpression が
true である場合、
lhs を LeftHandSideExpression
の StringValue とする。
rVal を AssignmentExpression の
NamedEvaluation (引数
lhs )の結果とする。
それ以外の場合、
rRef を AssignmentExpression の
? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? PutValue (lRef , rVal )
を実行する。
rVal を返す。
注
この式が strict mode code 内に出現する場合、1.e 、
3 、
2 、
2 、
2
における lRef が解決できない参照であれば、実行時エラー(ReferenceError
例外)がスローされる。さらに、
9 、
6 、
6 、
6
における lRef が、属性値 { [[Writable]] :
false } を持つ データプロパティ 、属性値 { [[Set]] : undefined } を持つ アクセサプロパティ 、または IsExtensible の返り値が
false であるオブジェクトの存在しないプロパティへの参照であった場合も、TypeError
例外がスローされる。
13.15.3 ApplyStringOrNumericBinaryOperator ( lVal ,
opText , rVal )
抽象操作 ApplyStringOrNumericBinaryOperator は、引数 lVal (ECMAScript
言語値 )、opText (**、*、/、%、+、-、<<、>>、>>>、&、^、または
|)、および rVal (ECMAScript
言語値 )を受け取り、通常完了(String、BigInt、またはNumberを含む) またはthrow
completion を返す。呼び出されたとき、次の手順を実行する:
opText が + の場合、
lPrim を ? ToPrimitive (lVal ) とする。
rPrim を ? ToPrimitive (rVal ) とする。
lPrim が String
であるか、rPrim が String
である場合、
lStr を ? ToString (lPrim )
とする。
rStr を ? ToString (rPrim )
とする。
lStr と rStr のstring-concatenation
を返す。
lVal に lPrim を設定する。
rVal に rPrim を設定する。
注:ここで、必ず数値演算になる。
lNum を ? ToNumeric (lVal ) とする。
rNum を ? ToNumeric (rVal ) とする。
SameType (lNum , rNum )
が false の場合、TypeError 例外をスローする。
lNum が BigInt の場合、
opText が ** の場合、? BigInt::exponentiate (lNum ,
rNum ) を返す。
opText が / の場合、? BigInt::divide (lNum ,
rNum ) を返す。
opText が % の場合、? BigInt::remainder (lNum ,
rNum ) を返す。
opText が >>> の場合、? BigInt::unsignedRightShift (lNum ,
rNum ) を返す。
operation を、次の表において opText に対応する抽象操作とする:
それ以外の場合、
アサート :
lNum は Number
である。
operation を、次の表において opText に対応する抽象操作とする:
operation (lNum , rNum ) を返す。
注1
ステップ ToPrimitive は、1.a および 1.b
で呼び出されるが、ヒントは与えられない。標準オブジェクトはDateを除き、ヒントがない場合は number
が与えられたかのように扱う。Dateはヒントがない場合 string が与えられたかのように扱う。エキゾチックオブジェクト は、ヒントがない場合に異なる方法で扱うことがある。
注2
ステップ 1.c は、3 の IsLessThan
アルゴリズムのステップと異なり、論理積ではなく論理和を用いている。
13.15.4 EvaluateStringOrNumericBinaryExpression (
leftOperand , opText , rightOperand )
抽象操作 EvaluateStringOrNumericBinaryExpression は、leftOperand (構文ノード )、opText (Unicodeコードポイントの列)、rightOperand (構文ノード )を引数とし、通常完了(String、BigInt、またはNumberを含む) またはabrupt
completion を返す。呼び出されたとき、次の手順を実行する:
lRef を leftOperand の ? Evaluation とする。
lVal を ? GetValue (lRef ) とする。
rRef を rightOperand の ? Evaluation とする。
rVal を ? GetValue (rRef ) とする。
? ApplyStringOrNumericBinaryOperator (lVal ,
opText , rVal ) を返す。
13.15.5 分割代入
補助構文
以下の生成規則のインスタンスを処理する際、特定の状況下では
AssignmentExpression
:
LeftHandSideExpression
=
AssignmentExpression
LeftHandSideExpression
の解釈は、次の文法を用いてより詳細に規定される:
AssignmentPattern [Yield,
Await] :
ObjectAssignmentPattern [?Yield,
?Await]
ArrayAssignmentPattern [?Yield,
?Await]
ObjectAssignmentPattern [Yield,
Await] :
{
}
{
AssignmentRestProperty [?Yield,
?Await]
}
{
AssignmentPropertyList [?Yield,
?Await]
}
{
AssignmentPropertyList [?Yield,
?Await]
,
AssignmentRestProperty [?Yield,
?Await] opt
}
ArrayAssignmentPattern [Yield,
Await] :
[
Elision opt
AssignmentRestElement [?Yield,
?Await] opt
]
[
AssignmentElementList [?Yield,
?Await]
]
[
AssignmentElementList [?Yield,
?Await]
,
Elision opt
AssignmentRestElement [?Yield,
?Await] opt
]
AssignmentRestProperty [Yield,
Await] :
...
DestructuringAssignmentTarget [?Yield,
?Await]
AssignmentPropertyList [Yield,
Await] :
AssignmentProperty [?Yield,
?Await]
AssignmentPropertyList [?Yield,
?Await]
,
AssignmentProperty [?Yield,
?Await]
AssignmentElementList [Yield,
Await] :
AssignmentElisionElement [?Yield,
?Await]
AssignmentElementList [?Yield,
?Await]
,
AssignmentElisionElement [?Yield,
?Await]
AssignmentElisionElement [Yield,
Await] :
Elision opt
AssignmentElement [?Yield,
?Await]
AssignmentProperty [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
PropertyName [?Yield,
?Await]
:
AssignmentElement [?Yield,
?Await]
AssignmentElement [Yield,
Await] :
DestructuringAssignmentTarget [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
AssignmentRestElement [Yield,
Await] :
...
DestructuringAssignmentTarget [?Yield,
?Await]
DestructuringAssignmentTarget [Yield,
Await] :
LeftHandSideExpression [?Yield,
?Await]
13.15.5.1 静的意味論:早期エラー
AssignmentProperty
:
IdentifierReference
Initializer opt
AssignmentRestProperty
:
...
DestructuringAssignmentTarget
DestructuringAssignmentTarget
: LeftHandSideExpression
13.15.5.2 実行時意味論:DestructuringAssignmentEvaluation
構文指示操作
DestructuringAssignmentEvaluation は引数 value (ECMAScript 言語値 )を取り、unused
を含む通常完了 またはabrupt
completion を返す。これは以下の生成規則ごとに定義される:
ObjectAssignmentPattern
:
{
}
? RequireObjectCoercible (value )
を実行する。
unused を返す。
ObjectAssignmentPattern
:
{
AssignmentPropertyList
}
{
AssignmentPropertyList
,
}
? RequireObjectCoercible (value )
を実行する。
? PropertyDestructuringAssignmentEvaluation
を AssignmentPropertyList と引数
value で実行する。
unused を返す。
ObjectAssignmentPattern
:
{
AssignmentRestProperty
}
? RequireObjectCoercible (value )
を実行する。
excludedNames を空の新しい List とする。
? RestDestructuringAssignmentEvaluation を
AssignmentRestProperty 、引数
value および excludedNames で実行した結果を返す。
ObjectAssignmentPattern
:
{
AssignmentPropertyList
,
AssignmentRestProperty
}
? RequireObjectCoercible (value )
を実行する。
excludedNames を ? PropertyDestructuringAssignmentEvaluation
を AssignmentPropertyList 、引数
value で実行した結果とする。
? RestDestructuringAssignmentEvaluation を
AssignmentRestProperty 、引数
value および excludedNames で実行した結果を返す。
ArrayAssignmentPattern
:
[
]
iteratorRecord を ? GetIterator (value ,
sync ) とする。
? IteratorClose (iteratorRecord ,
NormalCompletion (unused ))
を返す。
ArrayAssignmentPattern
:
[
Elision
]
iteratorRecord を ? GetIterator (value ,
sync ) とする。
result を Completion (IteratorDestructuringAssignmentEvaluation
を Elision 、引数
iteratorRecord で実行) とする。
iteratorRecord .[[Done]] が
false であれば、? IteratorClose (iteratorRecord ,
result ) を返す。
result を返す。
ArrayAssignmentPattern
:
[
Elision opt
AssignmentRestElement
]
iteratorRecord を ? GetIterator (value ,
sync ) とする。
Elision が存在する場合、
status を Completion (IteratorDestructuringAssignmentEvaluation
を Elision 、引数
iteratorRecord で実行) とする。
status が abrupt
completion であれば、
アサート :
iteratorRecord .[[Done]] は
true である。
? status を返す。
result を Completion (IteratorDestructuringAssignmentEvaluation
を AssignmentRestElement 、引数
iteratorRecord で実行) とする。
iteratorRecord .[[Done]] が
false であれば、? IteratorClose (iteratorRecord ,
result ) を返す。
result を返す。
ArrayAssignmentPattern
:
[
AssignmentElementList
]
iteratorRecord を ? GetIterator (value ,
sync ) とする。
result を Completion (IteratorDestructuringAssignmentEvaluation
を AssignmentElementList 、引数
iteratorRecord で実行) とする。
iteratorRecord .[[Done]] が
false であれば、? IteratorClose (iteratorRecord ,
result ) を返す。
result を返す。
ArrayAssignmentPattern
:
[
AssignmentElementList
,
Elision opt
AssignmentRestElement opt
]
iteratorRecord を ? GetIterator (value ,
sync ) とする。
status を Completion (IteratorDestructuringAssignmentEvaluation
を AssignmentElementList 、引数
iteratorRecord で実行) とする。
status が abrupt
completion であれば、
iteratorRecord .[[Done]] が
false であれば、? IteratorClose (iteratorRecord ,
status ) を返す。
? status を返す。
Elision が存在する場合、
status に Completion (IteratorDestructuringAssignmentEvaluation
を Elision 、引数
iteratorRecord で実行) を設定する。
status が abrupt
completion であれば、
アサート :
iteratorRecord .[[Done]] は
true である。
? status を返す。
AssignmentRestElement
が存在する場合、
status に Completion (IteratorDestructuringAssignmentEvaluation
を AssignmentRestElement
、引数 iteratorRecord で実行) を設定する。
iteratorRecord .[[Done]] が
false であれば、? IteratorClose (iteratorRecord ,
status ) を返す。
? status を返す。
13.15.5.3 実行時意味論:
PropertyDestructuringAssignmentEvaluation
構文指示操作
PropertyDestructuringAssignmentEvaluation は引数 value (ECMAScript 言語値 )を取り、property key の List
を含む通常完了 またはabrupt
completion を返す。これはすべての分割代入されたproperty
key のリストを収集する。以下の生成規則ごとに定義される:
AssignmentPropertyList
:
AssignmentPropertyList
,
AssignmentProperty
propertyNames を ? PropertyDestructuringAssignmentEvaluation
(AssignmentPropertyList 、引数
value )の結果とする。
nextNames を ? PropertyDestructuringAssignmentEvaluation
(AssignmentProperty 、引数
value )の結果とする。
propertyNames と nextNames のリスト連結 を返す。
AssignmentProperty
:
IdentifierReference
Initializer opt
P を IdentifierReference の
StringValue とする。
lRef を ? ResolveBinding (P ) とする。
v を ? GetV (value , P ) とする。
Initializer が存在し、かつ
v が undefined の場合、
IsAnonymousFunctionDefinition (Initializer ) が
true の場合、
v を ? NamedEvaluation (Initializer 、引数
P )の結果に設定する。
それ以外の場合、
defaultValue を ? Evaluation (Initializer ) とする。
v を ? GetValue (defaultValue )
に設定する。
? PutValue (lRef , v )
を実行する。
« P » を返す。
AssignmentProperty
:
PropertyName
:
AssignmentElement
name を ? Evaluation (PropertyName ) とする。
? KeyedDestructuringAssignmentEvaluation (AssignmentElement 、引数
value 、name )を実行する。
« name » を返す。
13.15.5.4 実行時意味論:
RestDestructuringAssignmentEvaluation
構文指示操作
RestDestructuringAssignmentEvaluation は引数 value (ECMAScript 言語値 )および
excludedNames (property key
のリスト )を受け取り、unused
を含む通常完了 またはabrupt
completion を返す。これは以下の生成規則ごとに定義される:
AssignmentRestProperty
:
...
DestructuringAssignmentTarget
lRef を DestructuringAssignmentTarget
の ? Evaluation とする。
restObj を OrdinaryObjectCreate (%Object.prototype% )
とする。
? CopyDataProperties (restObj ,
value , excludedNames ) を実行する。
? PutValue (lRef ,
restObj ) を返す。
13.15.5.5 実行時意味論:
IteratorDestructuringAssignmentEvaluation
構文指示操作
IteratorDestructuringAssignmentEvaluation は引数 iteratorRecord (イテレータレコード )を受け取り、unused
を含む通常完了 またはabrupt
completion を返す。これは以下の生成規則ごとに定義される:
AssignmentElementList
: AssignmentElisionElement
? IteratorDestructuringAssignmentEvaluation
を AssignmentElisionElement 、引数
iteratorRecord で実行し、その結果を返す。
AssignmentElementList
:
AssignmentElementList
,
AssignmentElisionElement
? IteratorDestructuringAssignmentEvaluation
を AssignmentElementList 、引数
iteratorRecord で実行する。
? IteratorDestructuringAssignmentEvaluation
を AssignmentElisionElement 、引数
iteratorRecord で実行し、その結果を返す。
AssignmentElisionElement
: AssignmentElement
? IteratorDestructuringAssignmentEvaluation
を AssignmentElement 、引数
iteratorRecord で実行し、その結果を返す。
AssignmentElisionElement
:
Elision
AssignmentElement
? IteratorDestructuringAssignmentEvaluation
を Elision 、引数
iteratorRecord で実行する。
? IteratorDestructuringAssignmentEvaluation
を AssignmentElement 、引数
iteratorRecord で実行し、その結果を返す。
Elision : ,
iteratorRecord .[[Done]] が
false の場合、
? IteratorStep (iteratorRecord )
を実行する。
unused を返す。
Elision :
Elision
,
? IteratorDestructuringAssignmentEvaluation
を Elision 、引数
iteratorRecord で実行する。
iteratorRecord .[[Done]] が
false の場合、
? IteratorStep (iteratorRecord )
を実行する。
unused を返す。
AssignmentElement
:
DestructuringAssignmentTarget
Initializer opt
DestructuringAssignmentTarget
が ObjectLiteral
でも ArrayLiteral
でもない場合、
lRef を DestructuringAssignmentTarget
の ? Evaluation
とする。
value を undefined とする。
iteratorRecord .[[Done]] が
false の場合、
next を ? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
value を next に設定する。
Initializer が存在し、かつ
value が undefined の場合、
IsAnonymousFunctionDefinition (Initializer ) が
true で、かつ IsIdentifierRef
of DestructuringAssignmentTarget
が true の場合、
target を DestructuringAssignmentTarget
の StringValue
とする。
v を Initializer の
? NamedEvaluation (引数
target )の結果に設定する。
それ以外の場合、
defaultValue を Initializer の
? Evaluation とする。
v を ? GetValue (defaultValue )
に設定する。
それ以外の場合、
v を value に設定する。
DestructuringAssignmentTarget
が ObjectLiteral
または ArrayLiteral
のいずれかである場合、
nestedAssignmentPattern を DestructuringAssignmentTarget
にカバーされている AssignmentPattern とする。
? DestructuringAssignmentEvaluation (nestedAssignmentPattern ,引数
v )の結果を返す。
? PutValue (lRef , v )
を返す。
注
左から右への評価順序は、分割代入パターンでない DestructuringAssignmentTarget
を イテレータ にアクセスする前や Initializer
を評価する前に評価することで維持される。
AssignmentRestElement
:
...
DestructuringAssignmentTarget
DestructuringAssignmentTarget
が ObjectLiteral
でも ArrayLiteral
でもない場合、
lRef を DestructuringAssignmentTarget
の ? Evaluation
とする。
A を ! ArrayCreate (0) とする。
n を 0 とする。
iteratorRecord .[[Done]] が
false の間、繰り返す:
next を ? IteratorStepValue (iteratorRecord )
とする。
next が done でない場合、
! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
next ) を実行する。
n を n + 1 に設定する。
DestructuringAssignmentTarget
が ObjectLiteral
でも ArrayLiteral
でもない場合、
? PutValue (lRef ,
A ) を返す。
nestedAssignmentPattern を DestructuringAssignmentTarget
にカバーされている AssignmentPattern
とする。
? DestructuringAssignmentEvaluation (nestedAssignmentPattern ,引数
A )の結果を返す。
13.15.5.6 実行時意味論:
KeyedDestructuringAssignmentEvaluation
構文指示操作
KeyedDestructuringAssignmentEvaluation は引数 value (ECMAScript 言語値 )および
propertyName (property key )を受け取り、unused
を含む通常完了 またはabrupt
completion を返す。これは以下の生成規則ごとに定義される:
AssignmentElement
:
DestructuringAssignmentTarget
Initializer opt
DestructuringAssignmentTarget
が ObjectLiteral
でも ArrayLiteral
でもない場合、
lRef を DestructuringAssignmentTarget
の ? Evaluation
とする。
v を ? GetV (value ,
propertyName ) とする。
Initializer が存在し、かつ
v が undefined の場合、
IsAnonymousFunctionDefinition (Initializer ) が
true で、かつ IsIdentifierRef
of DestructuringAssignmentTarget
が true の場合、
target を DestructuringAssignmentTarget
の StringValue
とする。
rhsValue を Initializer の
? NamedEvaluation (引数
target )の結果に設定する。
それ以外の場合、
defaultValue を Initializer の
? Evaluation とする。
rhsValue を ? GetValue (defaultValue )
に設定する。
それ以外の場合、
rhsValue を v に設定する。
DestructuringAssignmentTarget
が ObjectLiteral
または ArrayLiteral
のいずれかである場合、
assignmentPattern を DestructuringAssignmentTarget
にカバーされている AssignmentPattern とする。
? DestructuringAssignmentEvaluation (assignmentPattern ,引数
rhsValue )の結果を返す。
? PutValue (lRef ,
rhsValue ) を返す。
13.16 カンマ演算子(,)
構文
Expression [In, Yield,
Await] :
AssignmentExpression [?In,
?Yield, ?Await]
Expression [?In, ?Yield,
?Await]
,
AssignmentExpression [?In,
?Yield, ?Await]
13.16.1 実行時意味論:評価
Expression :
Expression
,
AssignmentExpression
lRef を Expression の ? Evaluation とする。
? GetValue (lRef ) を実行する。
rRef を AssignmentExpression の
? Evaluation とする。
? GetValue (rRef ) を返す。
注
GetValue
は、その値が使われない場合でも、観測可能な副作用がある可能性があるため呼び出さなければならない。
14 ECMAScript 言語:文および宣言
構文
Statement [Yield, Await,
Return] :
BlockStatement [?Yield, ?Await,
?Return]
VariableStatement [?Yield,
?Await]
EmptyStatement
ExpressionStatement [?Yield,
?Await]
IfStatement [?Yield, ?Await,
?Return]
BreakableStatement [?Yield,
?Await, ?Return]
ContinueStatement [?Yield,
?Await]
BreakStatement [?Yield,
?Await]
[+Return]
ReturnStatement [?Yield,
?Await]
WithStatement [?Yield, ?Await,
?Return]
LabelledStatement [?Yield,
?Await, ?Return]
ThrowStatement [?Yield,
?Await]
TryStatement [?Yield, ?Await,
?Return]
DebuggerStatement
Declaration [Yield,
Await] :
HoistableDeclaration [?Yield,
?Await, ~Default]
ClassDeclaration [?Yield, ?Await,
~Default]
LexicalDeclaration [+In,
?Yield, ?Await]
HoistableDeclaration [Yield,
Await, Default] :
FunctionDeclaration [?Yield,
?Await, ?Default]
GeneratorDeclaration [?Yield,
?Await, ?Default]
AsyncFunctionDeclaration [?Yield,
?Await, ?Default]
AsyncGeneratorDeclaration [?Yield,
?Await, ?Default]
BreakableStatement [Yield, Await,
Return] :
IterationStatement [?Yield,
?Await, ?Return]
SwitchStatement [?Yield, ?Await,
?Return]
14.1 文の意味論
14.1.1 実行時意味論:評価
HoistableDeclaration
:
GeneratorDeclaration
AsyncFunctionDeclaration
AsyncGeneratorDeclaration
empty を返す。
HoistableDeclaration
: FunctionDeclaration
? Evaluation (FunctionDeclaration )を返す。
BreakableStatement
:
IterationStatement
SwitchStatement
newLabelSet を空の新しい List
とする。
? LabelledEvaluation (この BreakableStatement ,引数
newLabelSet )を返す。
14.2 ブロック
構文
BlockStatement [Yield, Await,
Return] :
Block [?Yield, ?Await,
?Return]
Block [Yield, Await,
Return] :
{
StatementList [?Yield, ?Await,
?Return] opt
}
StatementList [Yield, Await,
Return] :
StatementListItem [?Yield,
?Await, ?Return]
StatementList [?Yield, ?Await,
?Return]
StatementListItem [?Yield,
?Await, ?Return]
StatementListItem [Yield, Await,
Return] :
Statement [?Yield, ?Await,
?Return]
Declaration [?Yield,
?Await]
14.2.1 静的意味論:早期エラー
Block :
{
StatementList
}
14.2.2 実行時意味論:評価
Block :
{
}
empty を返す。
Block :
{
StatementList
}
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
blockEnv を NewDeclarativeEnvironment (oldEnv )
とする。
BlockDeclarationInstantiation (StatementList ,blockEnv )を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を blockEnv に設定する。
blockValue を Completion (Evaluation (StatementList ))とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? blockValue を返す。
注1
制御が Block
からどのように離れても、LexicalEnvironment は必ず元の状態に戻る。
StatementList :
StatementList
StatementListItem
sl を StatementList の ? Evaluation とする。
s を Completion (StatementListItem の Evaluation )とする。
? UpdateEmpty (s , sl )
を返す。
注2
StatementList の値は、その
StatementList
内の最後の値を生成する項目の値である。例えば、次の eval 関数の呼び出しはすべて値 1 を返す:
eval ("1;;;;;" )
eval ("1;{}" )
eval ("1;var a;" )
14.2.3 BlockDeclarationInstantiation ( code ,
env )
抽象操作 BlockDeclarationInstantiation は、引数 code (構文ノード )、env (宣言型環境レコード )を受け取り、unused
を返す。code はそのブロックの本体に対応する 構文ノード である。env は束縛を作成する 環境レコード である。
注
Block または CaseBlock が評価されると、新しい
宣言型環境レコード
が作成され、そのブロック内で宣言された各ブロックスコープ変数、定数、関数、またはクラスの束縛が 環境レコード にインスタンス化される。
呼び出されたとき、次の手順を実行する:
declarations を code の LexicallyScopedDeclarations
とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
declarations の各要素 d について、
d の BoundNames の各要素
dn について、
IsConstantDeclaration (d )が
true である場合、
! env .CreateImmutableBinding(dn ,
true ) を実行する。
それ以外の場合、
! env .CreateMutableBinding(dn ,
false ) を実行する。注:このステップは B.3.2.6
で置き換えられる。
d が FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、または
AsyncGeneratorDeclaration
のいずれかである場合、
fn を d の BoundNames
の唯一の要素とする。
fo を InstantiateFunctionObject (d ,引数
env および privateEnv )の結果とする。
! env .InitializeBinding(fn , fo )
を実行する。注:このステップは B.3.2.6
で置き換えられる。
unused を返す。
14.3 宣言と変数文
14.3.1 let および const 宣言
注
let および const 宣言は、実行中の実行コンテキスト の
LexicalEnvironment にスコープされた変数を定義する。これらの変数は、内包する 環境レコード がインスタンス化されたときに作成されるが、その変数の
LexicalBinding
が評価されるまで、いかなる方法でもアクセスすることはできない。LexicalBinding が Initializer を持つ場合、その変数は
LexicalBinding の評価時に
Initializer の AssignmentExpression
の値に設定され、変数の作成時ではない。let 宣言内の LexicalBinding に Initializer がない場合は、LexicalBinding の評価時に変数は
undefined に設定される。
構文
LexicalDeclaration [In,
Yield, Await] :
LetOrConst
BindingList [?In, ?Yield,
?Await]
;
LetOrConst :
let
const
BindingList [In, Yield,
Await] :
LexicalBinding [?In,
?Yield, ?Await]
BindingList [?In, ?Yield,
?Await]
,
LexicalBinding [?In,
?Yield, ?Await]
LexicalBinding [In, Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await] opt
BindingPattern [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await]
14.3.1.1 静的意味論:早期エラー
LexicalDeclaration
:
LetOrConst
BindingList
;
LexicalBinding :
BindingIdentifier
Initializer opt
14.3.1.2 実行時意味論:評価
LexicalDeclaration
:
LetOrConst
BindingList
;
? Evaluation (BindingList )を実行する。
empty を返す。
BindingList :
BindingList
,
LexicalBinding
? Evaluation (BindingList )を実行する。
? Evaluation (LexicalBinding )を返す。
LexicalBinding :
BindingIdentifier
lhs を ! ResolveBinding (StringValue (BindingIdentifier ))とする。
! InitializeReferencedBinding (lhs ,undefined )を実行する。
empty を返す。
注
静的意味論 の規則により、この形式の LexicalBinding が
const 宣言で現れることはない。
LexicalBinding :
BindingIdentifier
Initializer
bindingId を BindingIdentifier の StringValue とする。
lhs を ! ResolveBinding (bindingId )とする。
IsAnonymousFunctionDefinition (Initializer )が
true の場合、
value を ? NamedEvaluation (Initializer ,引数
bindingId )とする。
それ以外の場合、
rhs を ? Evaluation (Initializer )とする。
value を ? GetValue (rhs )とする。
! InitializeReferencedBinding (lhs ,value )を実行する。
empty を返す。
LexicalBinding :
BindingPattern
Initializer
rhs を ? Evaluation (Initializer )とする。
value を ? GetValue (rhs )とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
? BindingInitialization (BindingPattern ,引数
value および env )を返す。
14.3.2 変数文
注
var 文は、実行中の実行コンテキスト の
VariableEnvironment にスコープされた変数を宣言する。var 変数は、それを内包する 環境レコード がインスタンス化されたときに作成され、作成時に
undefined に初期化される。任意の VariableEnvironment のスコープ内では、同じ BindingIdentifier
が複数の VariableDeclaration
で出現することがあるが、これらの宣言はまとめて1つの変数のみを定義する。VariableDeclaration が Initializer を持つ場合、その
VariableDeclaration の実行時に Initializer の AssignmentExpression
の値が代入され、変数の作成時ではない。
構文
VariableStatement [Yield,
Await] :
var
VariableDeclarationList [+In,
?Yield, ?Await]
;
VariableDeclarationList [In,
Yield, Await] :
VariableDeclaration [?In,
?Yield, ?Await]
VariableDeclarationList [?In,
?Yield, ?Await]
,
VariableDeclaration [?In,
?Yield, ?Await]
VariableDeclaration [In,
Yield, Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await] opt
BindingPattern [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await]
14.3.2.1 実行時意味論:評価
VariableStatement
:
var
VariableDeclarationList
;
? Evaluation (VariableDeclarationList )を実行する。
empty を返す。
VariableDeclarationList
:
VariableDeclarationList
,
VariableDeclaration
? Evaluation (VariableDeclarationList )を実行する。
? Evaluation (VariableDeclaration )を返す。
VariableDeclaration
: BindingIdentifier
empty を返す。
VariableDeclaration
:
BindingIdentifier
Initializer
bindingId を BindingIdentifier の StringValue とする。
lhs を ? ResolveBinding (bindingId )とする。
IsAnonymousFunctionDefinition (Initializer )が
true の場合、
value を ? NamedEvaluation (Initializer ,引数
bindingId )とする。
それ以外の場合、
rhs を ? Evaluation (Initializer )とする。
value を ? GetValue (rhs )とする。
? PutValue (lhs ,value )を実行する。
empty を返す。
注
VariableDeclaration が with
文内にネストされていて、VariableDeclaration 内の BindingIdentifier
が、その with 文の オブジェクト環境レコード
のバインディングオブジェクトの プロパティ名 と同じ場合、5
のステップは、そのプロパティに value を代入し、VariableEnvironment の Identifier の束縛には代入しない。
VariableDeclaration
:
BindingPattern
Initializer
rhs を ? Evaluation (Initializer )とする。
rVal を ? GetValue (rhs )とする。
? BindingInitialization (BindingPattern ,引数
rVal および undefined )を返す。
14.3.3 分割代入バインディングパターン
構文
BindingPattern [Yield,
Await] :
ObjectBindingPattern [?Yield,
?Await]
ArrayBindingPattern [?Yield,
?Await]
ObjectBindingPattern [Yield,
Await] :
{
}
{
BindingRestProperty [?Yield,
?Await]
}
{
BindingPropertyList [?Yield,
?Await]
}
{
BindingPropertyList [?Yield,
?Await]
,
BindingRestProperty [?Yield,
?Await] opt
}
ArrayBindingPattern [Yield,
Await] :
[
Elision opt
BindingRestElement [?Yield,
?Await] opt
]
[
BindingElementList [?Yield,
?Await]
]
[
BindingElementList [?Yield,
?Await]
,
Elision opt
BindingRestElement [?Yield,
?Await] opt
]
BindingRestProperty [Yield,
Await] :
...
BindingIdentifier [?Yield,
?Await]
BindingPropertyList [Yield,
Await] :
BindingProperty [?Yield,
?Await]
BindingPropertyList [?Yield,
?Await]
,
BindingProperty [?Yield,
?Await]
BindingElementList [Yield,
Await] :
BindingElisionElement [?Yield,
?Await]
BindingElementList [?Yield,
?Await]
,
BindingElisionElement [?Yield,
?Await]
BindingElisionElement [Yield,
Await] :
Elision opt
BindingElement [?Yield,
?Await]
BindingProperty [Yield,
Await] :
SingleNameBinding [?Yield,
?Await]
PropertyName [?Yield,
?Await]
:
BindingElement [?Yield,
?Await]
BindingElement [Yield,
Await] :
SingleNameBinding [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
SingleNameBinding [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
BindingRestElement [Yield,
Await] :
...
BindingIdentifier [?Yield,
?Await]
...
BindingPattern [?Yield,
?Await]
14.3.3.1 実行時意味論:PropertyBindingInitialization
構文指示操作
PropertyBindingInitialization は、引数 value (ECMAScript
言語値 )、environment (環境レコード またはundefined )を受け取り、property key の List
を含む通常完了 またはabrupt
completion を返す。すべての束縛されたプロパティ名のリストを収集する。以下の生成規則ごとに定義される:
BindingPropertyList
:
BindingPropertyList
,
BindingProperty
boundNames を ? PropertyBindingInitialization (BindingPropertyList ,引数
value および environment )の結果とする。
nextNames を ? PropertyBindingInitialization (BindingProperty ,引数
value および environment )の結果とする。
boundNames と nextNames のリスト連結 を返す。
BindingProperty
: SingleNameBinding
name を SingleNameBinding の BoundNames の唯一の要素とする。
? KeyedBindingInitialization (SingleNameBinding ,引数
value 、environment 、name )を実行する。
« name » を返す。
BindingProperty
:
PropertyName
:
BindingElement
P を ? Evaluation (PropertyName )の結果とする。
? KeyedBindingInitialization (BindingElement ,引数
value 、environment 、P )を実行する。
« P » を返す。
14.3.3.2 実行時意味論:RestBindingInitialization
構文指示操作
RestBindingInitialization は、引数 value (ECMAScript
言語値 )、environment (環境レコード またはundefined )、excludedNames (property key
のリスト )を受け取り、unused
を含む通常完了 またはabrupt
completion を返す。これは以下の生成規則ごとに定義される:
BindingRestProperty
:
...
BindingIdentifier
lhs を ? ResolveBinding (StringValue (BindingIdentifier ),environment )の結果とする。
restObj を OrdinaryObjectCreate (%Object.prototype% )とする。
? CopyDataProperties (restObj ,value ,excludedNames )を実行する。
environment が undefined の場合、? PutValue (lhs ,restObj )を返す。
? InitializeReferencedBinding (lhs ,restObj )を返す。
14.3.3.3 実行時意味論:KeyedBindingInitialization
構文指示操作
KeyedBindingInitialization は、引数 value (ECMAScript
言語値 )、environment (環境レコード またはundefined )、propertyName (property
key )を受け取り、unused
を含む通常完了 またはabrupt
completion を返す。
注
environment に undefined を渡した場合、初期化値の代入に PutValue
操作を使うことを示す。これは 非 strict 関数
の仮引数リストについて当てはまる。その場合、同じ名前のパラメータが複数ある可能性に対応するため、仮引数バインディングは事前に初期化される。
これは以下の生成規則ごとに定義される:
BindingElement :
BindingPattern
Initializer opt
v を ? GetV (value ,propertyName )の結果とする。
Initializer が存在し、かつ
v が undefined の場合、
defaultValue を ? Evaluation (Initializer )の結果とする。
v を ? GetValue (defaultValue )の結果に設定する。
? BindingInitialization (BindingPattern ,引数
v および environment )を返す。
SingleNameBinding
:
BindingIdentifier
Initializer opt
bindingId を BindingIdentifier の StringValue とする。
lhs を ? ResolveBinding (bindingId ,environment )の結果とする。
v を ? GetV (value ,propertyName )の結果とする。
Initializer が存在し、かつ
v が undefined の場合、
IsAnonymousFunctionDefinition (Initializer )が
true の場合、
v を ? NamedEvaluation (Initializer ,引数
bindingId )の結果に設定する。
それ以外の場合、
defaultValue を ? Evaluation (Initializer )の結果とする。
v を ? GetValue (defaultValue )の結果に設定する。
environment が undefined の場合、? PutValue (lhs ,v )を返す。
? InitializeReferencedBinding (lhs ,v )を返す。
14.4 空文
構文
EmptyStatement :
;
14.4.1 実行時意味論:評価
EmptyStatement :
;
empty を返す。
14.5 式文
構文
ExpressionStatement [Yield,
Await] :
[lookahead ∉ { { , function , async
[no LineTerminator here]
function , class , let
[ }]
Expression [+In, ?Yield,
?Await]
;
注
14.5.1 実行時意味論:評価
ExpressionStatement
:
Expression
;
exprRef を Expression の ? Evaluation とする。
? GetValue (exprRef )を返す。
14.6 if 文
構文
IfStatement [Yield, Await,
Return] :
if
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
else
Statement [?Yield, ?Await,
?Return]
if
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
[lookahead ≠ else ]
注
先読み制限 [lookahead ≠ else] は、古典的な「ぶら下がり
else」問題を通常の方法で解決する。つまり、どの if に対応するか曖昧な場合、else は候補となる if
のうち最も内側(最も近い)ものに関連付けられる。
14.6.1 静的意味論:早期エラー
IfStatement :
if
(
Expression
)
Statement
else
Statement
IfStatement :
if
(
Expression
)
Statement
注
この規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
14.6.2 実行時意味論:評価
IfStatement :
if
(
Expression
)
Statement
else
Statement
exprRef を Expression の ? Evaluation とする。
exprValue を ToBoolean (? GetValue (exprRef )) とする。
exprValue が true の場合、
stmtCompletion を Completion (Evaluation (最初の Statement )) とする。
それ以外の場合、
stmtCompletion を Completion (Evaluation (2番目の Statement )) とする。
? UpdateEmpty (stmtCompletion ,undefined )を返す。
IfStatement :
if
(
Expression
)
Statement
exprRef を Expression の ? Evaluation とする。
exprValue を ToBoolean (? GetValue (exprRef )) とする。
exprValue が false の場合、
undefined を返す。
それ以外の場合、
stmtCompletion を Completion (Evaluation (Statement )) とする。
? UpdateEmpty (stmtCompletion ,undefined )を返す。
14.7 反復文
構文
IterationStatement [Yield,
Await, Return] :
DoWhileStatement [?Yield,
?Await, ?Return]
WhileStatement [?Yield, ?Await,
?Return]
ForStatement [?Yield, ?Await,
?Return]
ForInOfStatement [?Yield,
?Await, ?Return]
14.7.1 意味論
14.7.1.1 LoopContinues ( completion ,
labelSet )
抽象操作 LoopContinues は、引数 completion (Completion
Record )および labelSet (文字列のリスト )を受け取り、Boolean
を返す。呼び出されると次の手順を実行する:
completion が normal
completion である場合、true を返す。
completion が continue
completion でない場合、false を返す。
completion .[[Target]] が
empty の場合、true を返す。
labelSet が completion .[[Target]]
を含む場合、true を返す。
false を返す。
注
14.7.1.2 実行時意味論:LoopEvaluation
構文指示操作
LoopEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。これは以下の生成規則ごとに定義される:
IterationStatement
: DoWhileStatement
? DoWhileLoopEvaluation (DoWhileStatement ,引数
labelSet )を返す。
IterationStatement
: WhileStatement
? WhileLoopEvaluation (WhileStatement ,引数
labelSet )を返す。
IterationStatement
: ForStatement
? ForLoopEvaluation (ForStatement ,引数
labelSet )を返す。
IterationStatement
: ForInOfStatement
? ForInOfLoopEvaluation (ForInOfStatement ,引数
labelSet )を返す。
14.7.2 do-while 文
構文
DoWhileStatement [Yield,
Await, Return] :
do
Statement [?Yield, ?Await,
?Return]
while
(
Expression [+In, ?Yield,
?Await]
)
;
14.7.2.1 静的意味論:早期エラー
DoWhileStatement
:
do
Statement
while
(
Expression
)
;
注
この規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
14.7.2.2 実行時意味論:DoWhileLoopEvaluation
構文指示操作
DoWhileLoopEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。これは以下の生成規則ごとに定義される:
DoWhileStatement
:
do
Statement
while
(
Expression
)
;
V を undefined とする。
繰り返す、
stmtResult を Completion (Evaluation (Statement )) とする。
LoopContinues (stmtResult ,
labelSet ) が false の場合、? UpdateEmpty (stmtResult ,
V ) を返す。
stmtResult .[[Value]] が
empty でない場合、V を stmtResult .[[Value]] に設定する。
exprRef を Expression の ? Evaluation とする。
exprValue を ? GetValue (exprRef ) とする。
ToBoolean (exprValue )
が false の場合、V を返す。
14.7.3 while 文
構文
WhileStatement [Yield, Await,
Return] :
while
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
14.7.3.1 静的意味論:早期エラー
WhileStatement :
while
(
Expression
)
Statement
注
この規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
14.7.3.2 実行時意味論:WhileLoopEvaluation
構文指示操作
WhileLoopEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。これは以下の生成規則ごとに定義される:
WhileStatement :
while
(
Expression
)
Statement
V を undefined とする。
繰り返す、
exprRef を Expression の ? Evaluation とする。
exprValue を ? GetValue (exprRef ) とする。
ToBoolean (exprValue )
が false の場合、V を返す。
stmtResult を Completion (Evaluation (Statement )) とする。
LoopContinues (stmtResult ,
labelSet ) が false の場合、? UpdateEmpty (stmtResult ,
V ) を返す。
stmtResult .[[Value]] が
empty でない場合、V を stmtResult .[[Value]] に設定する。
14.7.4 for 文
構文
ForStatement [Yield, Await,
Return] :
for
(
[lookahead ≠ let
[ ]
Expression [~In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
for
(
var
VariableDeclarationList [~In,
?Yield, ?Await]
;
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
for
(
LexicalDeclaration [~In,
?Yield, ?Await]
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
14.7.4.1 静的意味論:早期エラー
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
注
この規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
14.7.4.2 実行時意味論:ForLoopEvaluation
構文指示操作
ForLoopEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。これは以下の生成規則ごとに定義される:
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
最初の Expression
が存在する場合、
exprRef を 最初の Expression の ? Evaluation とする。
? GetValue (exprRef )を実行する。
2番目の Expression
が存在する場合、test を 2番目の Expression とし、そうでなければ test を
empty とする。
3番目の Expression
が存在する場合、increment を 3番目の Expression とし、そうでなければ
increment を empty とする。
? ForBodyEvaluation (test ,increment ,Statement ,« »,labelSet )を返す。
ForStatement :
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
? Evaluation (VariableDeclarationList )を実行する。
最初の Expression
が存在する場合、test を最初の Expression とし、そうでなければ test を
empty とする。
2番目の Expression
が存在する場合、increment を2番目の Expression とし、そうでなければ
increment を empty とする。
? ForBodyEvaluation (test ,increment ,Statement ,« »,labelSet )を返す。
ForStatement :
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
loopEnv を NewDeclarativeEnvironment (oldEnv )とする。
isConst を LexicalDeclaration の IsConstantDeclaration
とする。
boundNames を LexicalDeclaration の BoundNames とする。
boundNames の各要素 dn について、
isConst が true の場合、
! loopEnv .CreateImmutableBinding(dn ,true )
を実行する。
それ以外の場合、
! loopEnv .CreateMutableBinding(dn ,false )
を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を loopEnv に設定する。
forDcl を Completion (Evaluation (LexicalDeclaration )) とする。
forDcl が abrupt
completion の場合、
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? forDcl を返す。
isConst が false の場合、perIterationLets を
boundNames とし、そうでなければ perIterationLets を空の新しい List とする。
最初の Expression
が存在する場合、test を最初の Expression とし、そうでなければ test を
empty とする。
2番目の Expression
が存在する場合、increment を2番目の Expression とし、そうでなければ
increment を empty とする。
bodyResult を Completion (ForBodyEvaluation (test ,increment ,Statement ,perIterationLets ,labelSet ))
とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? bodyResult を返す。
14.7.4.3 ForBodyEvaluation ( test ,
increment , stmt , perIterationBindings , labelSet
)
抽象操作 ForBodyEvaluation は、引数 test (Expression 構文ノード または
empty )、increment (Expression 構文ノード または
empty )、stmt (Statement 構文ノード )、perIterationBindings (文字列のリスト )、labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。呼び出されると次の手順を実行する:
V を undefined とする。
? CreatePerIterationEnvironment (perIterationBindings )を実行する。
繰り返す、
test が empty でない場合、
testRef を test の ? Evaluation とする。
testValue を ? GetValue (testRef )とする。
ToBoolean (testValue )が
false の場合、V を返す。
result を stmt の Completion (Evaluation ) とする。
LoopContinues (result ,labelSet )が
false の場合、? UpdateEmpty (result ,V )を返す。
result .[[Value]] が
empty でない場合、V を result .[[Value]] に設定する。
? CreatePerIterationEnvironment (perIterationBindings )を実行する。
increment が empty でない場合、
incRef を increment の ? Evaluation とする。
? GetValue (incRef )を実行する。
14.7.4.4 CreatePerIterationEnvironment (
perIterationBindings )
抽象操作 CreatePerIterationEnvironment は、引数 perIterationBindings (文字列のリスト )を受け取り、unused
を含む通常完了 またはthrow
completion を返す。呼び出されると次の手順を実行する:
perIterationBindings に要素がある場合、
lastIterationEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
outer を lastIterationEnv .[[OuterEnv]] とする。
アサート :outer は
null ではない。
thisIterationEnv を NewDeclarativeEnvironment (outer )とする。
perIterationBindings の各要素 bn について、
! thisIterationEnv .CreateMutableBinding(bn ,false )
を実行する。
lastValue を
? lastIterationEnv .GetBindingValue(bn ,true )
とする。
! thisIterationEnv .InitializeBinding(bn ,lastValue )
を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を thisIterationEnv に設定する。
unused を返す。
14.7.5
for-in、for-of、および
for-await-of 文
構文
ForInOfStatement [Yield,
Await, Return] :
for
(
[lookahead ≠ let
[ ]
LeftHandSideExpression [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
var
ForBinding [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
ForDeclaration [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
[lookahead ∉ { let , async
of }]
LeftHandSideExpression [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
var
ForBinding [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
ForDeclaration [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
[lookahead ≠ let ]
LeftHandSideExpression [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
var
ForBinding [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
ForDeclaration [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
ForDeclaration [Yield,
Await] :
LetOrConst
ForBinding [?Yield,
?Await]
ForBinding [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
注
このセクションは附属書 B.3.5
により拡張されている。
14.7.5.1 静的意味論:早期エラー
ForInOfStatement
:
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
注
この規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
ForInOfStatement
:
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
ForInOfStatement
:
for
(
ForDeclaration
in
Expression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
14.7.5.2 静的意味論:IsDestructuring
構文指示操作
IsDestructuring は引数を取らず、Boolean を返す。これは次の生成規則ごとに定義される:
MemberExpression
: PrimaryExpression
PrimaryExpression が ObjectLiteral または
ArrayLiteral
のいずれかである場合、true を返す。
false を返す。
MemberExpression
:
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
MemberExpression
TemplateLiteral
SuperProperty
MetaProperty
new
MemberExpression
Arguments
MemberExpression
.
PrivateIdentifier
NewExpression :
new
NewExpression
LeftHandSideExpression
:
CallExpression
OptionalExpression
false を返す。
ForDeclaration :
LetOrConst
ForBinding
IsDestructuring (ForBinding )を返す。
ForBinding : BindingIdentifier
false を返す。
ForBinding : BindingPattern
true を返す。
注
このセクションは附属書 B.3.5
により拡張されている。
14.7.5.3 実行時意味論:ForDeclarationBindingInitialization
構文指示操作
ForDeclarationBindingInitialization は、引数 value (ECMAScript
言語値 )、environment (環境レコード または
undefined )を受け取り、unused を含む通常完了 または
abrupt completion
を返す。
注
environment に undefined を渡す場合は、初期化値の代入に PutValue
操作を使用することを示す。これは var 文や一部の 非 strict 関数
の仮引数リスト(10.2.11
を参照)で該当する。この場合、レキシカルバインディングは巻き上げられ、初期化子の評価前に事前初期化される。
これは次の生成規則ごとに定義される:
ForDeclaration :
LetOrConst
ForBinding
? BindingInitialization (ForBinding ,引数
value および environment )を返す。
14.7.5.4 実行時意味論:ForDeclarationBindingInstantiation
構文指示操作
ForDeclarationBindingInstantiation は、引数 environment (宣言的環境レコード )を受け取り、unused
を返す。これは次の生成規則ごとに定義される:
ForDeclaration :
LetOrConst
ForBinding
ForBinding の
BoundNames の各要素
name について、
LetOrConst の
IsConstantDeclaration
が true の場合、
! environment .CreateImmutableBinding(name ,true )
を実行する。
それ以外の場合、
! environment .CreateMutableBinding(name ,false )
を実行する。
unused を返す。
14.7.5.5 実行時意味論:ForInOfLoopEvaluation
構文指示操作
ForInOfLoopEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。これは次の生成規則ごとに定義される:
ForInOfStatement
:
for
(
LeftHandSideExpression
in
Expression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », Expression ,enumerate )とする。
? ForIn/OfBodyEvaluation (LeftHandSideExpression ,Statement ,keyResult ,enumerate ,assignment ,labelSet )を返す。
ForInOfStatement
:
for
(
var
ForBinding
in
Expression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », Expression ,enumerate )とする。
? ForIn/OfBodyEvaluation (ForBinding ,Statement ,keyResult ,enumerate ,var-binding ,labelSet )を返す。
ForInOfStatement
:
for
(
ForDeclaration
in
Expression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (BoundNames (ForDeclaration ),Expression ,enumerate )とする。
? ForIn/OfBodyEvaluation (ForDeclaration ,Statement ,keyResult ,enumerate ,lexical-binding ,labelSet )を返す。
ForInOfStatement
:
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression ,iterate )とする。
? ForIn/OfBodyEvaluation (LeftHandSideExpression ,Statement ,keyResult ,iterate ,assignment ,labelSet )を返す。
ForInOfStatement
:
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression ,iterate )とする。
? ForIn/OfBodyEvaluation (ForBinding ,Statement ,keyResult ,iterate ,var-binding ,labelSet )を返す。
ForInOfStatement
:
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (BoundNames (ForDeclaration ),AssignmentExpression ,iterate )とする。
? ForIn/OfBodyEvaluation (ForDeclaration ,Statement ,keyResult ,iterate ,lexical-binding ,labelSet )を返す。
ForInOfStatement
:
for
await
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression ,async-iterate )とする。
? ForIn/OfBodyEvaluation (LeftHandSideExpression ,Statement ,keyResult ,iterate ,assignment ,labelSet ,async )を返す。
ForInOfStatement
:
for
await
(
var
ForBinding
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (« », AssignmentExpression ,async-iterate )とする。
? ForIn/OfBodyEvaluation (ForBinding ,Statement ,keyResult ,iterate ,var-binding ,labelSet ,async )を返す。
ForInOfStatement
:
for
await
(
ForDeclaration
of
AssignmentExpression
)
Statement
keyResult を ? ForIn/OfHeadEvaluation (BoundNames (ForDeclaration ),AssignmentExpression ,async-iterate )とする。
? ForIn/OfBodyEvaluation (ForDeclaration ,Statement ,keyResult ,iterate ,lexical-binding ,labelSet ,async )を返す。
注
このセクションは附属書 B.3.5
により拡張されている。
14.7.5.6 ForIn/OfHeadEvaluation (
uninitializedBoundNames , expr , iterationKind )
抽象操作 ForIn/OfHeadEvaluation は、引数 uninitializedBoundNames (文字列のリスト )、expr (Expression 構文ノード または AssignmentExpression 構文ノード )、iterationKind (enumerate 、iterate 、または
async-iterate )を受け取り、Iterator Record
を含む通常完了 または abrupt completion
を返す。呼び出されると次の手順を実行する:
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
uninitializedBoundNames が空でない場合、
アサート :
uninitializedBoundNames に重複するエントリはない。
newEnv を NewDeclarativeEnvironment (oldEnv )とする。
uninitializedBoundNames の各文字列 name について、
! newEnv .CreateMutableBinding(name ,false )
を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を newEnv に設定する。
exprRef を Completion (Evaluation (expr )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
exprValue を ? GetValue (?
exprRef ) とする。
iterationKind が enumerate の場合、
exprValue が undefined または
null のいずれかである場合、
Completion
Record { [[Type]] :
break , [[Value]] :
empty , [[Target]] :
empty } を返す。
obj を ! ToObject (exprValue )とする。
iterator を EnumerateObjectProperties (obj )とする。
nextMethod を ! GetV (iterator ,"next" )とする。
Iterator Record { [[Iterator]] : iterator , [[NextMethod]] : nextMethod , [[Done]] : false } を返す。
それ以外の場合、
アサート :iterationKind は
iterate または async-iterate
のいずれかである。
iterationKind が async-iterate
の場合、iteratorKind を async とする。
それ以外の場合、iteratorKind を sync とする。
? GetIterator (exprValue ,iteratorKind )を返す。
14.7.5.7 ForIn/OfBodyEvaluation ( lhs ,
stmt , iteratorRecord , iterationKind , lhsKind ,
labelSet [ , iteratorKind ] )
抽象操作 ForIn/OfBodyEvaluation は、引数 lhs (構文ノード )、stmt (Statement 構文ノード )、iteratorRecord (Iterator
Record )、iterationKind (enumerate または
iterate )、lhsKind (assignment 、var-binding 、または
lexical-binding )、labelSet (文字列のリスト )、省略可能な引数
iteratorKind (sync または
async )を受け取り、ECMAScript
言語値を含む通常完了 またはabrupt completion
を返す。呼び出されると次の手順を実行する:
iteratorKind が存在しない場合、iteratorKind を
sync に設定する。
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
V を undefined とする。
destructuring を IsDestructuring (lhs )とする。
destructuring が true かつ lhsKind が
assignment の場合、
アサート :lhs は LeftHandSideExpression
である。
assignmentPattern を lhs によって カバーされる AssignmentPattern とする。
繰り返す、
nextResult を ? Call (iteratorRecord .[[NextMethod]] ,iteratorRecord .[[Iterator]] )とする。
iteratorKind が async
の場合、nextResult を ? Await (nextResult )に設定する。
nextResult が オブジェクトでない
場合、TypeError 例外をスローする。
done を ? IteratorComplete (nextResult )とする。
done が true の場合、V を返す。
nextValue を ? IteratorValue (nextResult )とする。
lhsKind が assignment または
var-binding のいずれかの場合、
destructuring が true の場合、
lhsKind が assignment の場合、
status を Completion (DestructuringAssignmentEvaluation
of assignmentPattern with argument
nextValue ) とする。
それ以外の場合、
アサート :
lhsKind は
var-binding である。
アサート :
lhs は ForBinding
である。
status を Completion (BindingInitialization
of lhs with arguments
nextValue および
undefined ) とする。
それ以外の場合、
lhsRef を Completion (Evaluation (lhs ))
とする。(繰り返し評価されることがある)
lhsKind が assignment かつ
lhs の AssignmentTargetType
が web-compat
である場合、ReferenceError 例外をスローする。
lhsRef が abrupt
completion の場合、
status を lhsRef とする。
それ以外の場合、
status を Completion (PutValue (lhsRef .[[Value]] ,
nextValue )) とする。
それ以外の場合、
アサート :lhsKind は
lexical-binding である。
アサート :lhs は ForDeclaration である。
iterationEnv を NewDeclarativeEnvironment (oldEnv )とする。
ForDeclarationBindingInstantiation
(lhs ,引数 iterationEnv )を実行する。
実行中の実行コンテキスト
の LexicalEnvironment を iterationEnv に設定する。
destructuring が true の場合、
status を Completion (ForDeclarationBindingInitialization
of lhs with arguments nextValue および
iterationEnv ) とする。
それ以外の場合、
アサート :lhs
は単一の名前を束縛する。
lhsName を LetOrConst の
BoundNames
の唯一の要素とする。
lhsRef を ! ResolveBinding (lhsName )とする。
status を Completion (InitializeReferencedBinding (lhsRef ,
nextValue )) とする。
status が abrupt
completion の場合、
実行中の実行コンテキスト
の LexicalEnvironment を oldEnv に設定する。
iteratorKind が async
の場合、? AsyncIteratorClose (iteratorRecord ,status )を返す。
iterationKind が enumerate の場合、
? status を返す。
それ以外の場合、
アサート :iterationKind
は iterate である。
? IteratorClose (iteratorRecord ,status )を返す。
result を Completion (Evaluation (stmt )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
LoopContinues (result ,labelSet )が
false の場合、
iterationKind が enumerate の場合、
? UpdateEmpty (result ,V )を返す。
それ以外の場合、
アサート :iterationKind
は iterate である。
status を Completion (UpdateEmpty (result ,V ))
に設定する。
iteratorKind が async
の場合、? AsyncIteratorClose (iteratorRecord ,status )を返す。
? IteratorClose (iteratorRecord ,status )を返す。
result .[[Value]] が
empty でない場合、V を result .[[Value]] に設定する。
14.7.5.8 実行時意味論:評価
BindingIdentifier
:
Identifier
yield
await
bindingId を BindingIdentifier の StringValue とする。
? ResolveBinding (bindingId )を返す。
14.7.5.9 EnumerateObjectProperties ( O )
抽象操作 EnumerateObjectProperties は引数 O (オブジェクト)を受け取り、イテレータオブジェクト を返す。呼び出されると次の手順を実行する:
O の enumerable プロパティのすべての文字列値キーを反復する next メソッドを持つ イテレータオブジェクト を返す。イテレータオブジェクト は ECMAScript
コードから直接アクセスされることはない。プロパティの列挙の仕組みや順序は規定されていないが、以下に指定する規則に従う必要がある。
イテレータ の throw および
return メソッドは null であり、呼び出されることはない。イテレータ の next
メソッドは、プロパティキー を イテレータ の値として返すべきかどうかを判定する。返される
プロパティキー
に Symbol は含まれない。列挙中にターゲットオブジェクトのプロパティが削除される場合がある。イテレータ の
next
メソッドで処理される前に削除されたプロパティは無視される。列挙中に新しいプロパティが追加された場合、それらが列挙の対象になる保証はない。プロパティ名
は、1回の列挙で最大1回のみ イテレータ の next
メソッドによって返される。
ターゲットオブジェクトのプロパティの列挙には、そのプロトタイプ、およびそのプロトタイプのプロトタイプといった具合に再帰的にプロトタイプのプロパティも含まれるが、プロトタイプのプロパティが、すでに
イテレータ の next
メソッドで処理されたものと同じ名前である場合、そのプロパティは処理されない。プロトタイプオブジェクトの enumerable プロパティ名は、そのプロトタイプオブジェクトを引数として
EnumerateObjectProperties を呼び出して取得しなければならない。EnumerateObjectProperties は、ターゲットオブジェクトの [[OwnPropertyKeys]] 内部メソッドを呼び出して、そのオブジェクト自身の プロパティキー
を取得しなければならない。ターゲットオブジェクトのプロパティ属性は、その [[GetOwnProperty]]
内部メソッドを呼び出して取得しなければならない。
さらに、O およびそのプロトタイプチェーン上のいずれのオブジェクトも Proxy
エキゾチックオブジェクト 、TypedArray 、モジュール名前空間エキゾチックオブジェクト 、または実装提供の
エキゾチックオブジェクト でない場合、イテレータ は イテレータ (CreateForInIterator (O ))と同様に動作しなければならない。ただし、次のいずれかが発生した場合を除く:
O またはプロトタイプチェーン上のオブジェクトの [[Prototype]]
内部スロットの値が変更された場合
O またはプロトタイプチェーン上のオブジェクトのプロパティが削除された場合
O のプロトタイプチェーン上のオブジェクトにプロパティが追加された場合
O またはプロトタイプチェーン上のオブジェクトのプロパティの [[Enumerable]]
属性の値が変更された場合
注 1
ECMAScript 実装は 14.7.5.10.2.1
のアルゴリズムを直接実装する必要はない。上記の段落の制約が破られない限り、そのアルゴリズムと動作が逸脱しない任意の実装方法を選択できる。
以下はこれらの規則に準拠する ECMAScript ジェネレータ関数の参考定義である:
function * EnumerateObjectProperties (obj) {
const visited = new Set ();
for (const key of Reflect .ownKeys (obj)) {
if (typeof key === "symbol" ) continue ;
const desc = Reflect .getOwnPropertyDescriptor (obj, key);
if (desc) {
visited.add (key);
if (desc.enumerable ) yield key;
}
}
const proto = Reflect .getPrototypeOf (obj);
if (proto === null ) return ;
for (const protoKey of EnumerateObjectProperties (proto)) {
if (!visited.has (protoKey)) yield protoKey;
}
}
注 2
エキゾチックオブジェクト のリストが
CreateForInIterator
に一致する必要がないとされているのは、歴史的にこれらの場合の実装が異なっていたためであり、それ以外では一致していたためである。
14.7.5.10 for-in イテレータオブジェクト
For-In
イテレータ は、特定のオブジェクトの反復を表すオブジェクトである。For-In イテレータオブジェクトは ECMAScript
コードから直接アクセスされることはなく、EnumerateObjectProperties
の動作を説明するためだけに存在する。
14.7.5.10.1 CreateForInIterator ( object )
抽象操作 CreateForInIterator は引数 object (オブジェクト)を受け取り、For-In イテレータ
を返す。これは、object の自身および継承された enumerable な文字列プロパティを特定の順序で反復する For-In イテレータオブジェクト
を作成するために使われる。呼び出されると次の手順を実行する:
iterator を OrdinaryObjectCreate (%ForInIteratorPrototype% ,«
[[Object]] , [[ObjectWasVisited]] , [[VisitedKeys]] , [[RemainingKeys]] »)とする。
iterator .[[Object]] に object
を設定する。
iterator .[[ObjectWasVisited]] に
false を設定する。
iterator .[[VisitedKeys]] に新しい空の リスト を設定する。
iterator .[[RemainingKeys]] に新しい空の リスト を設定する。
iterator を返す。
14.7.5.10.2 %ForInIteratorPrototype% オブジェクト
%ForInIteratorPrototype% オブジェクト:
14.7.5.10.2.1 %ForInIteratorPrototype%.next ( )
O を this とする。
アサート :O は オブジェクトである 。
アサート :O は For-In イテレータ
インスタンスのすべての内部スロットを持つ(14.7.5.10.3 )。
object を O .[[Object]] とする。
繰り返す、
O .[[ObjectWasVisited]] が
false の場合、
keys を ? object .[[OwnPropertyKeys]] ()
とする。
keys の各要素 key について、
key が 文字列
の場合、
key を O .[[RemainingKeys]]
に追加する。
O .[[ObjectWasVisited]] に
true を設定する。
O .[[RemainingKeys]] が空でない間、繰り返す、
r を O .[[RemainingKeys]] の最初の要素とする。
O .[[RemainingKeys]]
から最初の要素を削除する。
O .[[VisitedKeys]]
に r が含まれていない場合、
desc を ? object .[[GetOwnProperty]] (r )
とする。
desc が undefined
でない場合、
r を O .[[VisitedKeys]]
に追加する。
desc .[[Enumerable]] が
true の場合、CreateIteratorResultObject (r ,
false ) を返す。
object を ? object .[[GetPrototypeOf]] () に設定する。
O .[[Object]] を object
に設定する。
O .[[ObjectWasVisited]] を
false に設定する。
object が null の場合、CreateIteratorResultObject (undefined ,
true ) を返す。
14.7.5.10.3 for-in イテレータインスタンスのプロパティ
For-In イテレータ
インスタンスは、通常のオブジェクト であり、%ForInIteratorPrototype%
組み込みオブジェクトからプロパティを継承する。For-In イテレータ インスタンスは
表 38
にリストされている内部スロットで初期化される。
表 38: For-In イテレータ
インスタンスの内部スロット
内部スロット
型
説明
[[Object]]
オブジェクト
プロパティを反復しているオブジェクト値。
[[ObjectWasVisited]]
ブール値
true の場合、イテレータ が [[OwnPropertyKeys]] を [[Object]]
上で呼び出したことを示し、false の場合はまだ呼び出していないことを示す。
[[VisitedKeys]]
文字列のリスト
この イテレータ
でこれまでに返された値。
[[RemainingKeys]]
文字列のリスト
現在のオブジェクトのためにこれから返される値。プロトタイプ(プロトタイプが null
でない場合)はこれより後に反復される。
14.8 continue 文
構文
ContinueStatement [Yield,
Await] :
continue
;
continue
[ここに LineTerminator がない]
LabelIdentifier [?Yield,
?Await]
;
14.8.1 静的意味論:早期エラー
ContinueStatement
:
continue
;
continue
LabelIdentifier
;
14.8.2 実行時意味論:評価
ContinueStatement
:
continue
;
Completion
Record { [[Type]] :
continue , [[Value]] :
empty , [[Target]] :
empty } を返す。
ContinueStatement
:
continue
LabelIdentifier
;
label を LabelIdentifier の StringValue とする。
Completion
Record { [[Type]] :
continue , [[Value]] :
empty , [[Target]] :
label } を返す。
14.9 break 文
構文
BreakStatement [Yield,
Await] :
break
;
break
[ここに LineTerminator がない]
LabelIdentifier [?Yield,
?Await]
;
14.9.1 静的意味論:早期エラー
BreakStatement :
break
;
14.9.2 実行時意味論:評価
BreakStatement :
break
;
Completion
Record { [[Type]] :
break , [[Value]] :
empty , [[Target]] :
empty } を返す。
BreakStatement :
break
LabelIdentifier
;
label を LabelIdentifier の StringValue とする。
Completion
Record { [[Type]] :
break , [[Value]] :
empty , [[Target]] :
label } を返す。
14.10 return 文
構文
ReturnStatement [Yield,
Await] :
return
;
return
[ここに LineTerminator がない]
Expression [+In, ?Yield,
?Await]
;
注
return 文は関数の実行を停止し、ほとんどの場合、呼び出し元に値を返す。Expression が省略された場合、返り値は
undefined となる。それ以外の場合、返り値は Expression の値となる。return
文が実際に呼び出し元に値を返さない場合もあり得る。例えば、try ブロック内では、return 文の Completion Record は
finally ブロックの評価中に別の Completion
Record に置き換えられる場合がある。
14.10.1 実行時意味論:評価
ReturnStatement :
return
;
ReturnCompletion (undefined )
を返す。
ReturnStatement :
return
Expression
;
exprRef を ? Evaluation (Expression )とする。
exprValue を ? GetValue (exprRef ) とする。
GetGeneratorKind () が
async の場合、exprValue を ? Await (exprValue ) に設定する。
ReturnCompletion (exprValue )
を返す。
14.11 with 文
注 1
レガシー with 文の使用は新しい ECMAScript
コードでは推奨されません。strict モードコード と non-strict
コード の両方で許可されている 分割代入
などの代替手段を検討してください。
構文
WithStatement [Yield, Await,
Return] :
with
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
注 2
with 文は、計算されたオブジェクトに対して オブジェクト環境レコード を
実行中の実行コンテキスト
のレキシカル環境に追加します。その後、この拡張されたレキシカル環境を使って文を実行します。最後に元のレキシカル環境を復元します。
14.11.1 静的意味論:早期エラー
WithStatement :
with
(
Expression
)
Statement
注
2つ目の規則は B.3.1
で指定されている拡張が実装されている場合のみ適用される必要がある。
14.11.2 実行時意味論:評価
WithStatement :
with
(
Expression
)
Statement
val を ? Evaluation (Expression ) とする。
obj を ? ToObject (? GetValue (val )) とする。
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
newEnv を NewObjectEnvironment (obj ,
true , oldEnv ) とする。
実行中の実行コンテキスト の
LexicalEnvironment を newEnv に設定する。
C を Completion (Evaluation (Statement )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? UpdateEmpty (C ,
undefined ) を返す。
注
組み込みの Statement
からどのような制御で離脱しても(通常または何らかの abrupt
completion や例外による場合も)、LexicalEnvironment は常に元の状態に復元される。
14.12 switch 文
構文
SwitchStatement [Yield, Await,
Return] :
switch
(
Expression [+In, ?Yield,
?Await]
)
CaseBlock [?Yield, ?Await,
?Return]
CaseBlock [Yield, Await,
Return] :
{
CaseClauses [?Yield, ?Await,
?Return] opt
}
{
CaseClauses [?Yield, ?Await,
?Return] opt
DefaultClause [?Yield, ?Await,
?Return]
CaseClauses [?Yield, ?Await,
?Return] opt
}
CaseClauses [Yield, Await,
Return] :
CaseClause [?Yield, ?Await,
?Return]
CaseClauses [?Yield, ?Await,
?Return]
CaseClause [?Yield, ?Await,
?Return]
CaseClause [Yield, Await,
Return] :
case
Expression [+In, ?Yield,
?Await]
:
StatementList [?Yield, ?Await,
?Return] opt
DefaultClause [Yield, Await,
Return] :
default
:
StatementList [?Yield, ?Await,
?Return] opt
14.12.1 静的意味論:早期エラー
SwitchStatement :
switch
(
Expression
)
CaseBlock
14.12.2 実行時意味論:CaseBlockEvaluation
構文指示操作
CaseBlockEvaluation は、引数 input (ECMAScript
言語値 )を受け取り、ECMAScript
言語値を含む通常完了 または abrupt
completion を返す。これは次の生成規則ごとに定義される:
CaseBlock :
{
}
undefined を返す。
CaseBlock :
{
CaseClauses
}
V を undefined とする。
A を CaseClauses 内の CaseClause 項目のソーステキスト順の リスト とする。
found を false とする。
A の各 CaseClause C について、
found が false の場合、
found を ? CaseClauseIsSelected (C ,
input ) に設定する。
found が true の場合、
R を Completion (Evaluation (C ))
とする。
R .[[Value]] が
empty でない場合、V を R .[[Value]] に設定する。
R が abrupt
completion の場合、? UpdateEmpty (R ,
V ) を返す。
V を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
V を undefined とする。
最初の CaseClauses
が存在する場合、
A を最初の CaseClauses 内の CaseClause
項目のソーステキスト順リストとする。
それ以外の場合、
A を新しい空の リスト とする。
found を false とする。
A の各 CaseClause C について、
found が false の場合、
found を ? CaseClauseIsSelected (C ,
input ) に設定する。
found が true の場合、
R を Completion (Evaluation (C ))
とする。
R .[[Value]] が
empty でない場合、V を R .[[Value]] に設定する。
R が abrupt
completion の場合、? UpdateEmpty (R ,
V ) を返す。
foundInB を false とする。
2つ目の CaseClauses
が存在する場合、
B を2つ目の CaseClauses 内の CaseClause
項目のソーステキスト順リストとする。
それ以外の場合、
B を新しい空の リスト とする。
found が false の場合、
B の各 CaseClause C について、
foundInB が false の場合、
foundInB を ? CaseClauseIsSelected (C ,
input ) に設定する。
foundInB が true の場合、
R を Completion (Evaluation (CaseClause
C )) とする。
R .[[Value]] が
empty でない場合、V を
R .[[Value]] に設定する。
R が abrupt
completion の場合、? UpdateEmpty (R ,
V ) を返す。
foundInB が true の場合、V を返す。
defaultR を Completion (Evaluation (DefaultClause )) とする。
defaultR .[[Value]] が empty
でない場合、V を defaultR .[[Value]] に設定する。
defaultR が abrupt
completion の場合、? UpdateEmpty (defaultR ,
V ) を返す。
注:以下は2つ目の CaseClauses
の完全な反復である。
B の各 CaseClause C について、
R を Completion (Evaluation (CaseClause
C )) とする。
R .[[Value]] が empty
でない場合、V を R .[[Value]] に設定する。
R が abrupt
completion の場合、? UpdateEmpty (R ,
V ) を返す。
V を返す。
14.12.3 CaseClauseIsSelected ( C , input )
抽象操作 CaseClauseIsSelected は、引数 C (CaseClause 構文ノード )、input (ECMAScript 言語値 )を取り、Boolean を含む通常完了 または
abrupt completion
を返す。これは C が input にマッチするかどうかを判定する。呼び出されると次の手順を実行する:
アサート :
C は下記生成規則のインスタンスであること。
CaseClause :
case
Expression
:
StatementList opt
exprRef を ? Evaluation (C の Expression ) とする。
clauseSelector を ? GetValue (exprRef ) とする。
IsStrictlyEqual (input ,
clauseSelector ) を返す。
注
この操作は C の StatementList (存在する場合)を実行しない。CaseBlock
のアルゴリズムは、その戻り値を使ってどの StatementList から実行を開始するかを決定する。
14.12.4 実行時意味論:評価
SwitchStatement :
switch
(
Expression
)
CaseBlock
exprRef を ? Evaluation (Expression ) とする。
switchValue を ? GetValue (exprRef ) とする。
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
blockEnv を NewDeclarativeEnvironment (oldEnv )
とする。
BlockDeclarationInstantiation (CaseBlock ,
blockEnv ) を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を blockEnv に設定する。
R を Completion (CaseBlockEvaluation (CaseBlock ,
switchValue )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
R を返す。
注
どのような制御で SwitchStatement
から離脱しても、LexicalEnvironment は必ず元の状態に復元される。
CaseClause :
case
Expression
:
empty を返す。
CaseClause :
case
Expression
:
StatementList
? Evaluation (StatementList ) を返す。
DefaultClause :
default
:
empty を返す。
DefaultClause :
default
:
StatementList
? Evaluation (StatementList ) を返す。
14.13 ラベル付き文
構文
LabelledStatement [Yield, Await,
Return] :
LabelIdentifier [?Yield,
?Await]
:
LabelledItem [?Yield, ?Await,
?Return]
LabelledItem [Yield, Await,
Return] :
Statement [?Yield, ?Await,
?Return]
FunctionDeclaration [?Yield,
?Await, ~Default]
注
Statement
はラベルを前置することができる。ラベル付き文は、ラベル付きの break および continue
文と組み合わせてのみ使用される。ECMAScript には goto 文は存在しない。Statement は LabelledStatement の一部となり得て、それ自体が LabelledStatement
の一部となり得て……といった具合である。このように導入されたラベルは、個々の文の意味論を記述する際に「現在のラベル集合」と総称される。
14.13.1 静的意味論:早期エラー
LabelledItem : FunctionDeclaration
この生成規則にマッチするソーステキストがある場合、構文エラーとなる。
注
この規則の代替定義は B.3.1 に記載されている。
14.13.2 静的意味論:IsLabelledFunction ( stmt )
抽象操作 IsLabelledFunction は、引数 stmt (Statement 構文ノード )を受け取り、Boolean
を返す。呼び出されると次の手順を実行する:
stmt が LabelledStatement
でない場合、false を返す。
item を stmt の LabelledItem とする。
item が
LabelledItem
: FunctionDeclaration
である場合、true を返す。
subStmt を item の Statement とする。
IsLabelledFunction (subStmt )
を返す。
14.13.3 実行時意味論:評価
LabelledStatement
:
LabelIdentifier
:
LabelledItem
? LabelledEvaluation (この LabelledStatement ,引数
« »)を返す。
14.13.4 実行時意味論:LabelledEvaluation
構文指示操作
LabelledEvaluation は、引数 labelSet (文字列のリスト )を受け取り、ECMAScript 言語値または
empty を含む通常完了 または abrupt completion
を返す。これは次の生成規則ごとに定義される:
BreakableStatement
: IterationStatement
stmtResult を Completion (LoopEvaluation (IterationStatement ,引数
labelSet )) とする。
stmtResult が break
completion の場合、
stmtResult .[[Target]] が
empty の場合、
stmtResult .[[Value]] が
empty の場合、stmtResult を NormalCompletion (undefined )
に設定する。
それ以外の場合、stmtResult を NormalCompletion (stmtResult .[[Value]] ) に設定する。
? stmtResult を返す。
BreakableStatement
: SwitchStatement
stmtResult を Completion (Evaluation (SwitchStatement )) とする。
stmtResult が break
completion の場合、
stmtResult .[[Target]] が
empty の場合、
stmtResult .[[Value]] が
empty の場合、stmtResult を NormalCompletion (undefined )
に設定する。
それ以外の場合、stmtResult を NormalCompletion (stmtResult .[[Value]] ) に設定する。
? stmtResult を返す。
注 1
LabelledStatement
:
LabelIdentifier
:
LabelledItem
label を LabelIdentifier の StringValue とする。
newLabelSet を labelSet と « label » の リスト連結 とする。
stmtResult を Completion (LabelledEvaluation (LabelledItem ,引数 newLabelSet ))
とする。
stmtResult が break
completion かつ stmtResult .[[Target]] が label の場合、
stmtResult を NormalCompletion (stmtResult .[[Value]] ) に設定する。
? stmtResult を返す。
LabelledItem : FunctionDeclaration
? Evaluation (FunctionDeclaration ) を返す。
Statement :
BlockStatement
VariableStatement
EmptyStatement
ExpressionStatement
IfStatement
ContinueStatement
BreakStatement
ReturnStatement
WithStatement
ThrowStatement
TryStatement
DebuggerStatement
? Evaluation (Statement ) を返す。
注 2
Statement
の生成規則のうち、LabelledEvaluation に特別な意味論を持つのは BreakableStatement と LabelledStatement
の2つのみである。
14.14 throw 文
構文
ThrowStatement [Yield,
Await] :
throw
[ここに LineTerminator がない]
Expression [+In, ?Yield,
?Await]
;
14.14.1 実行時意味論:評価
ThrowStatement :
throw
Expression
;
exprRef を ? Evaluation (Expression ) とする。
exprValue を ? GetValue (exprRef ) とする。
ThrowCompletion (exprValue )
を返す。
14.15 try 文
構文
TryStatement [Yield, Await,
Return] :
try
Block [?Yield, ?Await,
?Return]
Catch [?Yield, ?Await,
?Return]
try
Block [?Yield, ?Await,
?Return]
Finally [?Yield, ?Await,
?Return]
try
Block [?Yield, ?Await,
?Return]
Catch [?Yield, ?Await,
?Return]
Finally [?Yield, ?Await,
?Return]
Catch [Yield, Await,
Return] :
catch
(
CatchParameter [?Yield,
?Await]
)
Block [?Yield, ?Await,
?Return]
catch
Block [?Yield, ?Await,
?Return]
Finally [Yield, Await,
Return] :
finally
Block [?Yield, ?Await,
?Return]
CatchParameter [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
注
try 文は、実行時エラーや throw 文などの例外的状況が発生しうるコードブロックを囲む。catch
節は例外処理コードを提供する。catch 節が例外を捕捉した時、その CatchParameter はその例外に束縛される。
14.15.1 静的意味論:早期エラー
Catch :
catch
(
CatchParameter
)
Block
注
この生成規則の代替の 静的意味論 は B.3.4 に記載されている。
14.15.2 実行時意味論:CatchClauseEvaluation
構文指示操作
CatchClauseEvaluation は、引数 thrownValue (ECMAScript 言語値 )を受け取り、ECMAScript 言語値または
empty を含む通常完了 または abrupt completion
を返す。これは次の生成規則ごとに定義される:
Catch :
catch
(
CatchParameter
)
Block
oldEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
catchEnv を NewDeclarativeEnvironment (oldEnv )
とする。
CatchParameter の
BoundNames の各要素
argName について、
! catchEnv .CreateMutableBinding(argName ,
false ) を実行する。
実行中の実行コンテキスト の
LexicalEnvironment を catchEnv に設定する。
status を Completion (BindingInitialization (CatchParameter , 引数
thrownValue , catchEnv )) とする。
status が abrupt
completion の場合、
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? status を返す。
B を Completion (Evaluation (Block )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を oldEnv に設定する。
? B を返す。
Catch :
catch
Block
? Evaluation (Block ) を返す。
注
どのような制御で Block
から離脱しても、LexicalEnvironment は必ず元の状態に復元される。
14.15.3 実行時意味論:評価
TryStatement :
try
Block
Catch
B を Completion (Evaluation (Block )) とする。
B が throw
completion の場合、C を Completion (CatchClauseEvaluation (Catch , B .[[Value]] )) とする。
それ以外の場合、C を B とする。
? UpdateEmpty (C ,
undefined ) を返す。
TryStatement :
try
Block
Finally
B を Completion (Evaluation (Block )) とする。
F を Completion (Evaluation (Finally )) とする。
F が normal
completion の場合、F を B に設定する。
? UpdateEmpty (F ,
undefined ) を返す。
TryStatement :
try
Block
Catch
Finally
B を Completion (Evaluation (Block )) とする。
B が throw
completion の場合、C を Completion (CatchClauseEvaluation (Catch , B .[[Value]] )) とする。
それ以外の場合、C を B とする。
F を Completion (Evaluation (Finally )) とする。
F が normal
completion の場合、F を C に設定する。
? UpdateEmpty (F ,
undefined ) を返す。
14.16 debugger 文
構文
DebuggerStatement :
debugger
;
14.16.1 実行時意味論:評価
注
DebuggerStatement
の評価は、デバッガ下で実行された場合に実装依存のブレークポイントを発生させることができる。デバッガが存在しない、またはアクティブでない場合、この文は観測可能な効果を持たない。
DebuggerStatement
:
debugger
;
実装依存のデバッグ機能が利用可能かつ有効であれば、
実装依存のデバッグ動作を行う。
新しい実装依存の Completion
Record を返す。
それ以外の場合、
empty を返す。
15 ECMAScript 言語:関数とクラス
注
様々な ECMAScript 言語要素は ECMAScript の 関数オブジェクト (10.2 )を生成する。これらの関数の 評価 は、その [[Call]] 内部メソッド(10.2.1 )の実行から開始される。
15.1 パラメータリスト
構文
UniqueFormalParameters [Yield,
Await] :
FormalParameters [?Yield,
?Await]
FormalParameters [Yield,
Await] :
[空]
FunctionRestParameter [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
,
FormalParameterList [?Yield,
?Await]
,
FunctionRestParameter [?Yield,
?Await]
FormalParameterList [Yield,
Await] :
FormalParameter [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
,
FormalParameter [?Yield,
?Await]
FunctionRestParameter [Yield,
Await] :
BindingRestElement [?Yield,
?Await]
FormalParameter [Yield,
Await] :
BindingElement [?Yield,
?Await]
15.1.1 静的意味論:早期エラー
UniqueFormalParameters
: FormalParameters
FormalParameters :
FormalParameterList
注
FormalParameterList 内で同じ BindingIdentifier
が複数回現れることが許されるのは、関数が単純なパラメータリストを持ち、かつ strict モードコード
で定義されていない場合のみである。
15.1.2 静的意味論:ContainsExpression
構文指示操作
ContainsExpression は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
ObjectBindingPattern
:
{
}
{
BindingRestProperty
}
false を返す。
ObjectBindingPattern
:
{
BindingPropertyList
,
BindingRestProperty
}
ContainsExpression (BindingPropertyList )を返す。
ArrayBindingPattern
:
[
Elision opt
]
false を返す。
ArrayBindingPattern
:
[
Elision opt
BindingRestElement
]
ContainsExpression (BindingRestElement )を返す。
ArrayBindingPattern
:
[
BindingElementList
,
Elision opt
]
ContainsExpression (BindingElementList )を返す。
ArrayBindingPattern
:
[
BindingElementList
,
Elision opt
BindingRestElement
]
has を ContainsExpression (BindingElementList )とする。
has が true の場合、true を返す。
ContainsExpression (BindingRestElement )を返す。
BindingPropertyList
:
BindingPropertyList
,
BindingProperty
has を ContainsExpression (BindingPropertyList )とする。
has が true の場合、true を返す。
ContainsExpression (BindingProperty )を返す。
BindingElementList
:
BindingElementList
,
BindingElisionElement
has を ContainsExpression (BindingElementList )とする。
has が true の場合、true を返す。
ContainsExpression (BindingElisionElement )を返す。
BindingElisionElement
:
Elision opt
BindingElement
ContainsExpression (BindingElement )を返す。
BindingProperty :
PropertyName
:
BindingElement
has を IsComputedPropertyKey (PropertyName )とする。
has が true の場合、true を返す。
ContainsExpression (BindingElement )を返す。
BindingElement :
BindingPattern
Initializer
true を返す。
SingleNameBinding
: BindingIdentifier
false を返す。
SingleNameBinding
:
BindingIdentifier
Initializer
true を返す。
BindingRestElement
:
...
BindingIdentifier
false を返す。
BindingRestElement
:
...
BindingPattern
ContainsExpression (BindingPattern )を返す。
FormalParameters :
[空]
false を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
ContainsExpression (FormalParameterList )が
true の場合、true を返す。
ContainsExpression (FunctionRestParameter )を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
ContainsExpression (FormalParameterList )が
true の場合、true を返す。
ContainsExpression (FormalParameter )を返す。
ArrowParameters :
BindingIdentifier
false を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals を CoverParenthesizedExpressionAndArrowParameterList
によって カバーされる ArrowFormalParameters とする。
ContainsExpression (formals )を返す。
AsyncArrowBindingIdentifier
: BindingIdentifier
false を返す。
15.1.3 静的意味論:IsSimpleParameterList
構文指示操作
IsSimpleParameterList は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
BindingElement :
BindingPattern
false を返す。
BindingElement :
BindingPattern
Initializer
false を返す。
SingleNameBinding
: BindingIdentifier
true を返す。
SingleNameBinding
:
BindingIdentifier
Initializer
false を返す。
FormalParameters :
[空]
true を返す。
FormalParameters :
FunctionRestParameter
false を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
false を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
IsSimpleParameterList (FormalParameterList )が
false の場合、false を返す。
IsSimpleParameterList (FormalParameter )を返す。
FormalParameter :
BindingElement
IsSimpleParameterList (BindingElement )を返す。
ArrowParameters :
BindingIdentifier
true を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals を CoverParenthesizedExpressionAndArrowParameterList
によって カバーされる ArrowFormalParameters とする。
IsSimpleParameterList (formals )を返す。
AsyncArrowBindingIdentifier
: BindingIdentifier
true を返す。
CoverCallExpressionAndAsyncArrowHead
:
MemberExpression
Arguments
head を CoverCallExpressionAndAsyncArrowHead
によって カバーされる AsyncArrowHead とする。
IsSimpleParameterList (head )を返す。
15.1.4 静的意味論:HasInitializer
構文指示操作
HasInitializer は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
BindingElement :
BindingPattern
false を返す。
BindingElement :
BindingPattern
Initializer
true を返す。
SingleNameBinding
: BindingIdentifier
false を返す。
SingleNameBinding
:
BindingIdentifier
Initializer
true を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
HasInitializer (FormalParameterList )が
true の場合、true を返す。
HasInitializer (FormalParameter )を返す。
15.1.5 静的意味論:ExpectedArgumentCount
構文指示操作
ExpectedArgumentCount は引数なしで呼び出され、非負の 整数 を返す。これは次の生成規則ごとに定義される:
FormalParameters :
[空]
FunctionRestParameter
0 を返す。
FormalParameters :
FormalParameterList
,
FunctionRestParameter
FormalParameterList の ExpectedArgumentCount
を返す。
注
FormalParameterList の
ExpectedArgumentCount は、rest パラメータまたは最初の FormalParameter が Initializer
を持つまでの左側の FormalParameters の数である。Initializer
を持たない FormalParameter が Initializer
を持つパラメータの後に現れることは許されているが、これらはデフォルト値 undefined を持つオプションとみなされる。
FormalParameterList
: FormalParameter
FormalParameter の
HasInitializer が
true の場合、0 を返す。
1 を返す。
FormalParameterList
:
FormalParameterList
,
FormalParameter
count を FormalParameterList の ExpectedArgumentCount
とする。
FormalParameterList の HasInitializer が
true 、または FormalParameter の HasInitializer が
true の場合、count を返す。
count + 1 を返す。
ArrowParameters :
BindingIdentifier
1 を返す。
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
formals を CoverParenthesizedExpressionAndArrowParameterList
によって カバーされる ArrowFormalParameters とする。
formals の ExpectedArgumentCount
を返す。
PropertySetParameterList
: FormalParameter
FormalParameter の
HasInitializer が
true の場合、0 を返す。
1 を返す。
AsyncArrowBindingIdentifier
: BindingIdentifier
1 を返す。
15.2 関数定義
構文
FunctionDeclaration [Yield,
Await, Default] :
function
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
[+Default]
function
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
FunctionExpression :
function
BindingIdentifier [~Yield,
~Await] opt
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
FunctionBody [Yield,
Await] :
FunctionStatementList [?Yield,
?Await]
FunctionStatementList [Yield,
Await] :
StatementList [?Yield, ?Await,
+Return] opt
15.2.1 静的意味論:早期エラー
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression
:
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
注
FunctionBody の
LexicallyDeclaredNames
には var や function 宣言によって束縛された識別子は含まれない。
FunctionBody : FunctionStatementList
15.2.2 静的意味論:FunctionBodyContainsUseStrict
構文指示操作
FunctionBodyContainsUseStrict は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
FunctionBody : FunctionStatementList
FunctionBody の
Directive Prologue に Use
Strict Directive が含まれていれば true を、そうでなければ
false を返す。
15.2.3 実行時意味論:EvaluateFunctionBody
構文指示操作
EvaluateFunctionBody は、引数 functionObject (ECMAScript 関数オブジェクト )、argumentsList (ECMAScript
言語値のリスト )を取り、return
completion または throw
completion を返す。これは次の生成規則ごとに定義される:
FunctionBody : FunctionStatementList
? FunctionDeclarationInstantiation (functionObject ,
argumentsList ) を実行する。
? Evaluation (FunctionStatementList ) を実行する。
注:前のステップが normal
completion となった場合、評価は FunctionStatementList
の末尾を通過して終了する。
ReturnCompletion (undefined )
を返す。
15.2.4 実行時意味論:InstantiateOrdinaryFunctionObject
構文指示操作
InstantiateOrdinaryFunctionObject は、引数 env (Environment
Record )、privateEnv (PrivateEnvironment Record
または null )を取り、ECMAScript の 関数オブジェクト を返す。これは次の生成規則ごとに定義される:
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
name を BindingIdentifier の StringValue とする。
sourceText を FunctionDeclaration にマッチした
ソーステキスト
とする。
F を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , FormalParameters , FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
name ) を実行する。
MakeConstructor (F ) を実行する。
F を返す。
FunctionDeclaration
:
function
(
FormalParameters
)
{
FunctionBody
}
sourceText を FunctionDeclaration にマッチした
ソーステキスト
とする。
F を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , FormalParameters , FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
"default" ) を実行する。
MakeConstructor (F ) を実行する。
F を返す。
注
匿名の FunctionDeclaration は
export default 宣言の一部としてのみ現れ、その関数コードは常に strict
モードコード となる。
15.2.5 実行時意味論:InstantiateOrdinaryFunctionExpression
構文指示操作
InstantiateOrdinaryFunctionExpression は、オプションの引数 name (property key または Private
Name )を取り、ECMAScript の 関数オブジェクト を返す。これは次の生成規則ごとに定義される:
FunctionExpression
:
function
(
FormalParameters
)
{
FunctionBody
}
name が存在しない場合、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を FunctionExpression にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , FormalParameters , FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
MakeConstructor (closure )
を実行する。
closure を返す。
FunctionExpression
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
アサート :name は存在しない。
name を BindingIdentifier の StringValue に設定する。
outerEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
funcEnv を NewDeclarativeEnvironment (outerEnv )
とする。
! funcEnv .CreateImmutableBinding(name ,
false ) を実行する。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を FunctionExpression にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , FormalParameters , FunctionBody ,
non-lexical-this , funcEnv , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
MakeConstructor (closure )
を実行する。
! funcEnv .InitializeBinding(name , closure ) を実行する。
closure を返す。
注
15.2.6 実行時意味論:評価
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
empty を返す。
注 1
FunctionDeclaration
:
function
(
FormalParameters
)
{
FunctionBody
}
empty を返す。
FunctionExpression
:
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
InstantiateOrdinaryFunctionExpression (FunctionExpression )
を返す。
注 2
FunctionDeclaration または FunctionExpression
で定義された全ての関数には "prototype" プロパティが自動的に作成され、それが constructor
として使用される可能性がある。
FunctionStatementList
: [空]
undefined を返す。
15.3 アロー関数定義
構文
ArrowFunction [In, Yield,
Await] :
ArrowParameters [?Yield,
?Await]
[ここに LineTerminator がない]
=>
ConciseBody [?In]
ArrowParameters [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
ConciseBody [In]
:
[先読み ≠ { ]
ExpressionBody [?In,
~Await]
{
FunctionBody [~Yield,
~Await]
}
ExpressionBody [In,
Await] :
AssignmentExpression [?In,
~Yield, ?Await]
補足構文
次の生成規則のインスタンスを処理する際
ArrowParameters [Yield,
Await] : CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList
の解釈は、以下の文法を用いて精緻化される:
ArrowFormalParameters [Yield,
Await] :
(
UniqueFormalParameters [?Yield,
?Await]
)
15.3.1 静的意味論:早期エラー
ArrowFunction :
ArrowParameters
=>
ConciseBody
ArrowParameters :
CoverParenthesizedExpressionAndArrowParameterList
15.3.2 静的意味論:ConciseBodyContainsUseStrict
構文指示操作
ConciseBodyContainsUseStrict は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
ConciseBody : ExpressionBody
false を返す。
ConciseBody :
{
FunctionBody
}
FunctionBodyContainsUseStrict (FunctionBody ) を返す。
15.3.3 実行時意味論:EvaluateConciseBody
構文指示操作
EvaluateConciseBody は、引数 functionObject (ECMAScript 関数オブジェクト )、argumentsList (ECMAScript
言語値のリスト )を取り、return
completion または throw
completion を返す。これは次の生成規則ごとに定義される:
ConciseBody : ExpressionBody
? FunctionDeclarationInstantiation (functionObject ,
argumentsList ) を実行する。
? Evaluation (ExpressionBody ) を返す。
15.3.4 実行時意味論:InstantiateArrowFunctionExpression
構文指示操作
InstantiateArrowFunctionExpression は、オプションの引数 name (property key または Private
Name )を取り、ECMAScript の 関数オブジェクト を返す。これは次の生成規則ごとに定義される:
ArrowFunction :
ArrowParameters
=>
ConciseBody
name が存在しない場合、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を ArrowFunction にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , ArrowParameters , ConciseBody ,
lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
closure を返す。
注
ArrowFunction は
arguments、super、this、new.target
のローカル束縛を定義しない。ArrowFunction 内で
arguments、super、this、new.target
への参照は、静的に囲まれた環境の束縛に解決されなければならない。通常は、直近の囲まれた関数の Function Environment となる。ArrowFunction が
super への参照を含んでいても、手順 5 で生成された
関数オブジェクト は MakeMethod
によってメソッド化されない。ArrowFunction が super
を参照する場合、それは必ず非ArrowFunction
の中に含まれており、super を実装するために必要な状態は ArrowFunction の 関数オブジェクト がキャプチャする env
を通じて利用可能となる。
15.3.5 実行時意味論:評価
ArrowFunction :
ArrowParameters
=>
ConciseBody
InstantiateArrowFunctionExpression (ArrowFunction ) を返す。
ExpressionBody :
AssignmentExpression
exprRef を ? Evaluation (AssignmentExpression ) とする。
exprValue を ? GetValue (exprRef ) とする。
ReturnCompletion (exprValue )
を返す。
15.4 メソッド定義
構文
MethodDefinition [Yield,
Await] :
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
GeneratorMethod [?Yield,
?Await]
AsyncMethod [?Yield,
?Await]
AsyncGeneratorMethod [?Yield,
?Await]
get
ClassElementName [?Yield,
?Await]
(
)
{
FunctionBody [~Yield,
~Await]
}
set
ClassElementName [?Yield,
?Await]
(
PropertySetParameterList
)
{
FunctionBody [~Yield,
~Await]
}
PropertySetParameterList
:
FormalParameter [~Yield,
~Await]
15.4.1 静的意味論:早期エラー
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
MethodDefinition :
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
15.4.2 静的意味論:HasDirectSuper
構文指示操作
HasDirectSuper は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
UniqueFormalParameters
Contains (SuperCall ) が
true の場合、true を返す。
FunctionBody Contains (SuperCall ) を返す。
MethodDefinition :
get
ClassElementName
(
)
{
FunctionBody
}
FunctionBody Contains (SuperCall ) を返す。
MethodDefinition :
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
PropertySetParameterList
Contains (SuperCall ) が
true の場合、true を返す。
FunctionBody Contains (SuperCall ) を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
UniqueFormalParameters
Contains (SuperCall ) が
true の場合、true を返す。
GeneratorBody
Contains (SuperCall ) を返す。
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
UniqueFormalParameters
Contains (SuperCall ) が
true の場合、true を返す。
AsyncGeneratorBody Contains (SuperCall ) を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
UniqueFormalParameters
Contains (SuperCall ) が
true の場合、true を返す。
AsyncFunctionBody
Contains (SuperCall ) を返す。
15.4.3 静的意味論:SpecialMethod
構文指示操作
SpecialMethod は引数なしで呼び出され、Boolean を返す。これは次の生成規則ごとに定義される:
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
false を返す。
MethodDefinition :
GeneratorMethod
AsyncMethod
AsyncGeneratorMethod
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
true を返す。
15.4.4 実行時意味論:DefineMethod
構文指示操作
DefineMethod は、引数 object (Object)、オプション引数
functionPrototype (Object)を取り、ECMAScript
言語値を含む通常完了 (Record (フィールド
[[Key]] (property key )、[[Closure]] (ECMAScript function object )))または abrupt completion
を返す。これは次の生成規則ごとに定義される:
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
functionPrototype が存在する場合、
prototype を functionPrototype に設定する。
それ以外の場合、
prototype を %Function.prototype%
に設定する。
sourceText を MethodDefinition にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (prototype ,
sourceText , UniqueFormalParameters , FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
Record { [[Key]] : propKey , [[Closure]] : closure } を返す。
15.4.5 実行時意味論:MethodDefinitionEvaluation
構文指示操作
MethodDefinitionEvaluation は、引数
object (Object)、enumerable (Boolean)を受け取り、ECMAScript
言語値を含む通常完了 (PrivateElement または
unused )、もしくは abrupt
completion を返す。これは次の生成規則ごとに定義される:
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
methodDef を ? DefineMethod (MethodDefinition , 引数
object ) とする。
SetFunctionName (methodDef .[[Closure]] , methodDef .[[Key]] ) を実行する。
? DefineMethodProperty (object ,
methodDef .[[Key]] , methodDef .[[Closure]] , enumerable ) を返す。
MethodDefinition :
get
ClassElementName
(
)
{
FunctionBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を MethodDefinition にマッチした ソーステキスト
とする。
formalParameterList を以下の生成規則のインスタンスとする:
FormalParameters
: [空]
closure を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , formalParameterList , FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
SetFunctionName (closure ,
propKey , "get" ) を実行する。
propKey が Private Name であれば、
PrivateElement
{ [[Key]] : propKey , [[Kind]] : accessor , [[Get]] : closure , [[Set]] : undefined } を返す。
それ以外の場合、
desc を PropertyDescriptor { [[Get]] :
closure , [[Enumerable]] :
enumerable , [[Configurable]] :
true } とする。
? DefinePropertyOrThrow (object ,
propKey , desc ) を実行する。
unused を返す。
MethodDefinition :
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を MethodDefinition にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , PropertySetParameterList ,
FunctionBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
SetFunctionName (closure ,
propKey , "set" ) を実行する。
propKey が Private Name であれば、
PrivateElement
{ [[Key]] : propKey , [[Kind]] : accessor , [[Get]] : undefined , [[Set]] : closure } を返す。
それ以外の場合、
desc を PropertyDescriptor { [[Set]] :
closure , [[Enumerable]] :
enumerable , [[Configurable]] :
true } とする。
? DefinePropertyOrThrow (object ,
propKey , desc ) を実行する。
unused を返す。
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を GeneratorMethod にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%GeneratorFunction.prototype% ,
sourceText , UniqueFormalParameters , GeneratorBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
SetFunctionName (closure ,
propKey ) を実行する。
prototype を OrdinaryObjectCreate (%GeneratorPrototype% )
とする。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
? DefineMethodProperty (object ,
propKey , closure , enumerable ) を返す。
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を AsyncGeneratorMethod にマッチした
ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% ,
sourceText , UniqueFormalParameters , AsyncGeneratorBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
SetFunctionName (closure ,
propKey ) を実行する。
prototype を OrdinaryObjectCreate (%AsyncGeneratorPrototype% )
とする。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
? DefineMethodProperty (object ,
propKey , closure , enumerable ) を返す。
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
propKey を ? Evaluation (ClassElementName ) とする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を AsyncMethod にマッチした ソーステキスト
とする。
closure を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , UniqueFormalParameters , AsyncFunctionBody ,
non-lexical-this , env , privateEnv ) とする。
MakeMethod (closure ,
object ) を実行する。
SetFunctionName (closure ,
propKey ) を実行する。
? DefineMethodProperty (object ,
propKey , closure , enumerable ) を返す。
15.5 ジェネレーター関数定義
構文
GeneratorDeclaration [Yield,
Await, Default] :
function
*
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
[+Default]
function
*
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorExpression
:
function
*
BindingIdentifier [+Yield,
~Await] opt
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorMethod [Yield,
Await] :
*
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorBody :
FunctionBody [+Yield,
~Await]
YieldExpression [In,
Await] :
yield
yield
[ここに LineTerminator がない]
AssignmentExpression [?In,
+Yield, ?Await]
yield
[ここに LineTerminator がない]
*
AssignmentExpression [?In,
+Yield, ?Await]
注 1
注 2
YieldExpression
はジェネレーター関数の FormalParameters 内で使用できない。なぜなら FormalParameters
の一部となる式は、生成される Generator が再開可能な状態になる前に評価されるためである。
注 3
ジェネレーターに関する 抽象操作 は
27.5.3 で定義されている。
15.5.1 静的意味論:早期エラー
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression
:
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
15.5.2 実行時意味論:EvaluateGeneratorBody
構文指示操作
EvaluateGeneratorBody は引数 functionObject (ECMAScript 関数オブジェクト )、argumentsList (ECMAScript
言語値のリスト )を受け取り、throw
completion または return
completion を返す。これは次の生成規則ごとに定義される:
GeneratorBody :
FunctionBody
? FunctionDeclarationInstantiation (functionObject ,
argumentsList ) を実行する。
G を ? OrdinaryCreateFromConstructor (functionObject ,
"%GeneratorPrototype%" , « [[GeneratorState]] , [[GeneratorContext]] , [[GeneratorBrand]] ») とする。
G .[[GeneratorBrand]] を empty
に設定する。
G .[[GeneratorState]] を
suspended-start に設定する。
GeneratorStart (G , FunctionBody ) を実行する。
ReturnCompletion (G ) を返す。
15.5.3 実行時意味論:InstantiateGeneratorFunctionObject
構文指示操作
InstantiateGeneratorFunctionObject は引数 env (Environment
Record )、privateEnv (PrivateEnvironment Record
または null )を受け取り、ECMAScript 関数オブジェクト を返す。これは次の生成規則ごとに定義される:
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
name を BindingIdentifier の StringValue に設定する。
sourceText を GeneratorDeclaration にマッチした
ソーステキスト
に設定する。
F を OrdinaryFunctionCreate (%GeneratorFunction.prototype% ,
sourceText , FormalParameters , GeneratorBody ,
non-lexical-this , env , privateEnv ) に設定する。
SetFunctionName (F ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%GeneratorPrototype% )
に設定する。
! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
F を返す。
GeneratorDeclaration
:
function
*
(
FormalParameters
)
{
GeneratorBody
}
sourceText を GeneratorDeclaration にマッチした
ソーステキスト
に設定する。
F を OrdinaryFunctionCreate (%GeneratorFunction.prototype% ,
sourceText , FormalParameters , GeneratorBody ,
non-lexical-this , env , privateEnv ) に設定する。
SetFunctionName (F ,
"default" ) を実行する。
prototype を OrdinaryObjectCreate (%GeneratorPrototype% )
に設定する。
! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
F を返す。
注
匿名の GeneratorDeclaration は
export default 宣言の一部としてのみ現れ、その関数コードは常に strict
モードコード となる。
15.5.4 実行時意味論:InstantiateGeneratorFunctionExpression
構文指示操作
InstantiateGeneratorFunctionExpression はオプション引数 name (property key または Private
Name )を受け取り、ECMAScript 関数オブジェクト を返す。これは次の生成規則ごとに定義される:
GeneratorExpression
:
function
*
(
FormalParameters
)
{
GeneratorBody
}
name が存在しない場合、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を GeneratorExpression にマッチした
ソーステキスト
に設定する。
closure を OrdinaryFunctionCreate (%GeneratorFunction.prototype% ,
sourceText , FormalParameters , GeneratorBody ,
non-lexical-this , env , privateEnv ) に設定する。
SetFunctionName (closure ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%GeneratorPrototype% )
に設定する。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
closure を返す。
GeneratorExpression
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
アサート :
name は存在しない。
name を BindingIdentifier の StringValue に設定する。
outerEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
funcEnv を NewDeclarativeEnvironment (outerEnv )
に設定する。
! funcEnv .CreateImmutableBinding(name ,
false ) を実行する。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を GeneratorExpression にマッチした
ソーステキスト
に設定する。
closure を OrdinaryFunctionCreate (%GeneratorFunction.prototype% ,
sourceText , FormalParameters , GeneratorBody ,
non-lexical-this , funcEnv , privateEnv )
に設定する。
SetFunctionName (closure ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%GeneratorPrototype% )
に設定する。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
! funcEnv .InitializeBinding(name ,
closure ) を実行する。
closure を返す。
注
15.5.5 実行時意味論:評価
GeneratorExpression
:
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
InstantiateGeneratorFunctionExpression (GeneratorExpression ) を返す。
YieldExpression :
yield
? Yield (undefined ) を返す。
YieldExpression :
yield
AssignmentExpression
exprRef を ? Evaluation (AssignmentExpression ) とする。
value を ? GetValue (exprRef ) とする。
? Yield (value ) を返す。
YieldExpression :
yield
*
AssignmentExpression
generatorKind を GetGeneratorKind () とする。
アサート :generatorKind は
sync または async のいずれかである。
exprRef を ? Evaluation (AssignmentExpression ) とする。
value を ? GetValue (exprRef ) とする。
iteratorRecord を ? GetIterator (value ,
generatorKind ) とする。
iterator を iteratorRecord .[[Iterator]]
とする。
received を NormalCompletion (undefined )
とする。
繰り返す、
received が normal
completion なら、
innerResult を ? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] , « received .[[Value]] ») とする。
generatorKind が async
なら、innerResult を ? Await (innerResult )
に設定する。
innerResult がオブジェクトでない場合 、TypeError
例外をスローする。
done を ? IteratorComplete (innerResult )
とする。
done が true なら、
? IteratorValue (innerResult )
を返す。
generatorKind が async
なら、received を Completion (AsyncGeneratorYield (?
IteratorValue (innerResult )))
に設定する。
それ以外の場合、received を Completion (GeneratorYield (innerResult ))
に設定する。
それ以外で received が throw
completion なら、
throw を ? GetMethod (iterator ,
"throw" ) とする。
throw が undefined でない場合、
innerResult を ? Call (throw ,
iterator , « received .[[Value]] ») とする。
generatorKind が async
なら、innerResult を ? Await (innerResult )
に設定する。
注:内部 イテレータ の
throw メソッドからの例外は伝播する。内部 throw メソッドからの
Normal
completions は内部 next
と同様に処理される。
innerResult がオブジェクトでない場合 、TypeError
例外をスローする。
done を ? IteratorComplete (innerResult )
とする。
done が true なら、
? IteratorValue (innerResult )
を返す。
generatorKind が async
なら、received を Completion (AsyncGeneratorYield (?
IteratorValue (innerResult )))
に設定する。
それ以外の場合、received を Completion (GeneratorYield (innerResult ))
に設定する。
それ以外の場合、
注:iterator に throw メソッドがない場合、この throw で
yield* ループが終了する。ただしまず iterator
にクリーンアップの機会を与える必要がある。
closeCompletion を NormalCompletion (empty )
に設定する。
generatorKind が async
なら、? AsyncIteratorClose (iteratorRecord ,
closeCompletion ) を実行する。
それ以外の場合、? IteratorClose (iteratorRecord ,
closeCompletion ) を実行する。
注:次のステップは TypeError をスローし、yield*
プロトコル違反を示す:iterator に throw メソッドがない。
TypeError 例外をスローする。
それ以外の場合、
アサート :received は
return
completion である。
return を ? GetMethod (iterator ,
"return" ) とする。
return が undefined の場合、
value を received .[[Value]] に設定する。
generatorKind が async の場合、
value を ? Await (value )
に設定する。
ReturnCompletion (value )
を返す。
innerReturnResult を ? Call (return ,
iterator , « received .[[Value]] ») に設定する。
generatorKind が async
の場合、innerReturnResult を ? Await (innerReturnResult )
に設定する。
innerReturnResult がオブジェクトでない場合 、TypeError
例外をスローする。
done を ? IteratorComplete (innerReturnResult )
に設定する。
done が true の場合、
value を ? IteratorValue (innerReturnResult )
に設定する。
ReturnCompletion (value )
を返す。
generatorKind が async
の場合、received を Completion (AsyncGeneratorYield (?
IteratorValue (innerReturnResult )))
に設定する。
それ以外の場合、received を Completion (GeneratorYield (innerReturnResult ))
に設定する。
15.6 非同期ジェネレーター関数定義
構文
AsyncGeneratorDeclaration [Yield,
Await, Default] :
async
[ここに LineTerminator はありません]
function
*
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
[+Default]
async
[ここに LineTerminator はありません]
function
*
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
[ここに LineTerminator はありません]
function
*
BindingIdentifier [+Yield,
+Await] opt
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorMethod [Yield,
Await] :
async
[ここに LineTerminator はありません]
*
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorBody :
FunctionBody [+Yield,
+Await]
注1
YieldExpression および
AwaitExpression
は、非同期ジェネレーター関数の FormalParameters 内では使用できません。なぜなら、FormalParameters
の一部として評価される式は、生成される AsyncGenerator が再開可能な状態になる前に評価されるためです。
注2
AsyncGenerator に関連する
抽象操作 は、27.6.3
に定義されています。
15.6.1 静的意味論:早期エラー
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
15.6.2 実行時意味論: EvaluateAsyncGeneratorBody
構文指示操作
EvaluateAsyncGeneratorBody は
引数 functionObject (ECMAScriptの 関数オブジェクト )および argumentsList (
List で、ECMAScript言語値 のリスト)を取り、
throw completion または
return completion を返します。
以下の生成規則に対して部分的に定義されます:
AsyncGeneratorBody
: FunctionBody
? FunctionDeclarationInstantiation (functionObject ,
argumentsList ) を実行する。
generator を ? OrdinaryCreateFromConstructor (functionObject ,
"%AsyncGeneratorPrototype%" , « [[AsyncGeneratorState]] , [[AsyncGeneratorContext]] , [[AsyncGeneratorQueue]] , [[GeneratorBrand]] ») とする。
generator .[[GeneratorBrand]] に
empty を設定する。
generator .[[AsyncGeneratorState]] に
suspended-start を設定する。
AsyncGeneratorStart (generator ,
FunctionBody ) を実行する。
ReturnCompletion (generator )
を返す。
15.6.3 実行時意味論: InstantiateAsyncGeneratorFunctionObject
構文指示操作
InstantiateAsyncGeneratorFunctionObject は
引数 env (Environment Record )および
privateEnv (PrivateEnvironment Record または
null )を取り、ECMAScriptの 関数オブジェクト を返します。
以下の生成規則に対して部分的に定義されます:
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
name を、StringValue (BindingIdentifier
の)とする。
sourceText を 一致したソーステキスト (AsyncGeneratorDeclaration
の)とする。
F を OrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% ,
sourceText , FormalParameters , AsyncGeneratorBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%AsyncGeneratorPrototype% )
とする。
! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
F を返す。
AsyncGeneratorDeclaration
:
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
sourceText を 一致したソーステキスト (AsyncGeneratorDeclaration
の)とする。
F を OrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% ,
sourceText , FormalParameters , AsyncGeneratorBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
"default" ) を実行する。
prototype を OrdinaryObjectCreate (%AsyncGeneratorPrototype% )
とする。
! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
F を返す。
注
匿名の AsyncGeneratorDeclaration は
export default 宣言の一部としてのみ出現可能です。
15.6.4 実行時意味論: InstantiateAsyncGeneratorFunctionExpression
構文指示操作
InstantiateAsyncGeneratorFunctionExpression は
オプションの引数 name (プロパティキー または Private Name )を受け取り、
ECMAScriptの 関数オブジェクト を返します。
以下の生成規則に対して部分的に定義されます:
AsyncGeneratorExpression
:
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
name が存在しない場合、name に "" を設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncGeneratorExpression
の)とする。
closure を OrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% ,
sourceText , FormalParameters , AsyncGeneratorBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%AsyncGeneratorPrototype% )
とする。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
closure を返す。
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
Assert :
name は存在しない。
name を StringValue (BindingIdentifier
の)とする。
outerEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
funcEnv を NewDeclarativeEnvironment (outerEnv )
とする。
! funcEnv .CreateImmutableBinding(name ,
false ) を実行する。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncGeneratorExpression
の)とする。
closure を OrdinaryFunctionCreate (%AsyncGeneratorFunction.prototype% ,
sourceText , FormalParameters , AsyncGeneratorBody ,
non-lexical-this , funcEnv , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
prototype を OrdinaryObjectCreate (%AsyncGeneratorPrototype% )
とする。
! DefinePropertyOrThrow (closure ,
"prototype" , PropertyDescriptor { [[Value]] :
prototype , [[Writable]] : true ,
[[Enumerable]] : false , [[Configurable]] : false }) を実行する。
! funcEnv .InitializeBinding(name ,
closure ) を実行する。
closure を返す。
注
15.6.5 実行時意味論: 評価
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
InstantiateAsyncGeneratorFunctionExpression
(AsyncGeneratorExpression )
を返す。
15.7 クラス定義
構文
ClassDeclaration [Yield, Await,
Default] :
class
BindingIdentifier [?Yield,
?Await]
ClassTail [?Yield,
?Await]
[+Default]
class
ClassTail [?Yield,
?Await]
ClassExpression [Yield,
Await] :
class
BindingIdentifier [?Yield,
?Await] opt
ClassTail [?Yield,
?Await]
ClassTail [Yield,
Await] :
ClassHeritage [?Yield,
?Await] opt
{
ClassBody [?Yield,
?Await] opt
}
ClassHeritage [Yield,
Await] :
extends
LeftHandSideExpression [?Yield,
?Await]
ClassBody [Yield,
Await] :
ClassElementList [?Yield,
?Await]
ClassElementList [Yield,
Await] :
ClassElement [?Yield,
?Await]
ClassElementList [?Yield,
?Await]
ClassElement [?Yield,
?Await]
ClassElement [Yield,
Await] :
MethodDefinition [?Yield,
?Await]
static
MethodDefinition [?Yield,
?Await]
FieldDefinition [?Yield,
?Await]
;
static
FieldDefinition [?Yield,
?Await]
;
ClassStaticBlock
;
FieldDefinition [Yield,
Await] :
ClassElementName [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
ClassElementName [Yield,
Await] :
PropertyName [?Yield,
?Await]
PrivateIdentifier
ClassStaticBlock :
static
{
ClassStaticBlockBody
}
ClassStaticBlockBody
:
ClassStaticBlockStatementList
ClassStaticBlockStatementList
:
StatementList [~Yield, +Await,
~Return] opt
注
15.7.1 静的意味論:早期エラー
ClassTail :
ClassHeritage opt
{
ClassBody
}
ClassBody : ClassElementList
ClassElement : MethodDefinition
ClassElement :
static
MethodDefinition
ClassElement :
FieldDefinition
;
ClassElement :
static
FieldDefinition
;
FieldDefinition :
ClassElementName
Initializer opt
ClassElementName :
PrivateIdentifier
ClassStaticBlockBody
: ClassStaticBlockStatementList
15.7.2 静的意味論: ClassElementKind
構文指示操作
ClassElementKind は
引数を取らず、constructor-method 、non-constructor-method 、または
empty を返します。以下の生成規則ごとに部分的に定義されます:
ClassElement : MethodDefinition
MethodDefinition の
PropName が
"constructor" の場合、
constructor-method を返す。
non-constructor-method を返す。
ClassElement :
static
MethodDefinition
FieldDefinition
;
static
FieldDefinition
;
non-constructor-method を返す。
ClassElement : ClassStaticBlock
non-constructor-method を返す。
ClassElement : ;
empty を返す。
15.7.3 静的意味論: ConstructorMethod
構文指示操作
ConstructorMethod は
引数を取らず、ClassElement
構文ノード
または empty を返します。以下の生成規則ごとに部分的に定義されます:
ClassElementList :
ClassElement
ClassElement の
ClassElementKind が
constructor-method の場合、ClassElement を返す。
empty を返す。
ClassElementList :
ClassElementList
ClassElement
head を ConstructorMethod
(ClassElementList
の)とする。
head が empty でない場合、head を返す。
ClassElement の
ClassElementKind が
constructor-method の場合、ClassElement を返す。
empty を返す。
注
早期エラー規則により、"constructor" という名前のメソッド定義が1つしか存在せず、
それがアクセサプロパティ や
ジェネレーター定義でないことが保証されます。
15.7.4 静的意味論: IsStatic
構文指示操作
IsStatic は
引数を取らず、Boolean を返します。以下の生成規則ごとに部分的に定義されます:
ClassElement : MethodDefinition
false を返す。
ClassElement :
static
MethodDefinition
true を返す。
ClassElement :
FieldDefinition
;
false を返す。
ClassElement :
static
FieldDefinition
;
true を返す。
ClassElement : ClassStaticBlock
true を返す。
ClassElement : ;
false を返す。
15.7.5 静的意味論: NonConstructorElements
構文指示操作
NonConstructorElements は
引数を取らず、List (ClassElement
構文ノード のリスト)を返します。
以下の生成規則ごとに部分的に定義されます:
ClassElementList :
ClassElement
ClassElement の
ClassElementKind が
non-constructor-method の場合、
« ClassElement » を返す。
新しい空の List を返す。
ClassElementList :
ClassElementList
ClassElement
list を NonConstructorElements
(ClassElementList
の)とする。
ClassElement の
ClassElementKind が
non-constructor-method の場合、
ClassElement を
list の末尾に追加する。
list を返す。
15.7.6 静的意味論: PrototypePropertyNameList
構文指示操作
PrototypePropertyNameList は
引数を取らず、List (プロパティキー
のリスト)を返します。
以下の生成規則ごとに部分的に定義されます:
ClassElementList :
ClassElement
propName を ClassElement の
PropName とする。
propName が empty である場合、新しい空の List を返す。
ClassElement の
IsStatic が
true の場合、
新しい空の List を返す。
« propName » を返す。
ClassElementList :
ClassElementList
ClassElement
list を PrototypePropertyNameList
(ClassElementList
の)とする。
propName を ClassElement の
PropName とする。
propName が empty の場合、list を返す。
ClassElement の
IsStatic が
true の場合、
list を返す。
list と « propName » の リスト結合 を返す。
15.7.7 静的意味論: AllPrivateIdentifiersValid
構文指示操作
AllPrivateIdentifiersValid は
引数 names (文字列のリスト )を受け取り、Boolean
を返します。
この仕様の以下に示されていないすべての文法生成規則の選択肢は、AllPrivateIdentifiersValid のデフォルト定義を暗黙的に持ちます:
この 構文ノード の各子ノード child について、
child が非終端記号のインスタンスである場合、
AllPrivateIdentifiersValid
(child と引数 names )が false
なら、false を返す。
true を返す。
MemberExpression :
MemberExpression
.
PrivateIdentifier
names に PrivateIdentifier の
StringValue が含まれる場合、
AllPrivateIdentifiersValid
(MemberExpression と引数
names )を返す。
false を返す。
CallExpression :
CallExpression
.
PrivateIdentifier
names に PrivateIdentifier の
StringValue が含まれる場合、
AllPrivateIdentifiersValid
(CallExpression と引数
names )を返す。
false を返す。
OptionalChain :
?.
PrivateIdentifier
names に PrivateIdentifier の
StringValue
が含まれる場合、true を返す。
false を返す。
OptionalChain :
OptionalChain
.
PrivateIdentifier
names に PrivateIdentifier の
StringValue が含まれる場合、
AllPrivateIdentifiersValid
(OptionalChain と引数
names )を返す。
false を返す。
ClassBody : ClassElementList
newNames を names と PrivateBoundIdentifiers
(ClassBody の)との リスト結合 とする。
AllPrivateIdentifiersValid
(ClassElementList
と引数 newNames )を返す。
RelationalExpression
:
PrivateIdentifier
in
ShiftExpression
names に PrivateIdentifier の
StringValue が含まれる場合、
AllPrivateIdentifiersValid
(ShiftExpression と引数
names )を返す。
false を返す。
15.7.8 静的意味論: PrivateBoundIdentifiers
構文指示操作
PrivateBoundIdentifiers は
引数を取らず、文字列のリスト を返します。以下の生成規則ごとに部分的に定義されます:
FieldDefinition :
ClassElementName
Initializer opt
PrivateBoundIdentifiers
(ClassElementName
の)を返す。
ClassElementName :
PrivateIdentifier
唯一の要素が PrivateIdentifier の
StringValue である
List を返す。
ClassElementName :
PropertyName
ClassElement :
ClassStaticBlock
;
新しい空の List を返す。
ClassElementList :
ClassElementList
ClassElement
names1 を PrivateBoundIdentifiers
(ClassElementList
の)とする。
names2 を PrivateBoundIdentifiers
(ClassElement の)とする。
names1 と names2 の リスト結合 を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
PrivateBoundIdentifiers
(ClassElementName
の)を返す。
15.7.9 静的意味論: ContainsArguments
構文指示操作
ContainsArguments は
引数を取らず、Boolean を返します。
この仕様の以下に示されていないすべての文法生成規則の選択肢は、ContainsArguments のデフォルト定義を暗黙的に持ちます:
この 構文ノード の各子ノード child について、
child が非終端記号のインスタンスである場合、
ContainsArguments
(child ) が true なら、true
を返す。
false を返す。
IdentifierReference
: Identifier
Identifier の
StringValue が
"arguments" なら、
true を返す。
false を返す。
FunctionDeclaration
:
function
BindingIdentifier
(
FormalParameters
)
{
FunctionBody
}
function
(
FormalParameters
)
{
FunctionBody
}
FunctionExpression
:
function
BindingIdentifier opt
(
FormalParameters
)
{
FunctionBody
}
GeneratorDeclaration
:
function
*
BindingIdentifier
(
FormalParameters
)
{
GeneratorBody
}
function
*
(
FormalParameters
)
{
GeneratorBody
}
GeneratorExpression
:
function
*
BindingIdentifier opt
(
FormalParameters
)
{
GeneratorBody
}
AsyncGeneratorDeclaration
:
async
function
*
BindingIdentifier
(
FormalParameters
)
{
AsyncGeneratorBody
}
async
function
*
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
function
*
BindingIdentifier opt
(
FormalParameters
)
{
AsyncGeneratorBody
}
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
false を返す。
MethodDefinition :
ClassElementName
(
UniqueFormalParameters
)
{
FunctionBody
}
get
ClassElementName
(
)
{
FunctionBody
}
set
ClassElementName
(
PropertySetParameterList
)
{
FunctionBody
}
GeneratorMethod :
*
ClassElementName
(
UniqueFormalParameters
)
{
GeneratorBody
}
AsyncGeneratorMethod
:
async
*
ClassElementName
(
UniqueFormalParameters
)
{
AsyncGeneratorBody
}
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
ContainsArguments
(ClassElementName
の)を返す。
15.7.10 実行時意味論: ClassFieldDefinitionEvaluation
構文指示操作
ClassFieldDefinitionEvaluation は
引数 homeObject (オブジェクト)を取り、
正常完了(
ClassFieldDefinition
Record
を含む)または
異常完了
を返します。以下の生成規則ごとに部分的に定義されます:
FieldDefinition :
ClassElementName
Initializer opt
name を ? Evaluation (ClassElementName
の)とする。
Initializer が存在する場合、
formalParameterList を
FormalParameters
: [empty]
の生成規則のインスタンスとする。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を空の Unicode コードポイント列とする。
initializer を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , formalParameterList , Initializer ,
non-lexical-this , env , privateEnv )
とする。
MakeMethod (initializer ,
homeObject ) を実行する。
initializer .[[ClassFieldInitializerName]] に
name を設定する。
それ以外の場合、
initializer を empty とする。
ClassFieldDefinition
Record
{ [[Name]] : name , [[Initializer]] : initializer } を返す。
注
initializer 用に作成された関数は ECMAScript コードから直接アクセスされることはありません。
15.7.11 実行時意味論: ClassStaticBlockDefinitionEvaluation
構文指示操作
ClassStaticBlockDefinitionEvaluation は
引数 homeObject (オブジェクト)を取り、
ClassStaticBlockDefinition
Record
を返します。以下の生成規則ごとに部分的に定義されます:
ClassStaticBlock :
static
{
ClassStaticBlockBody
}
lex を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を空の Unicode コードポイント列とする。
formalParameters を
FormalParameters
: [empty]
の生成規則のインスタンスとする。
bodyFunction を OrdinaryFunctionCreate (%Function.prototype% ,
sourceText , formalParameters , ClassStaticBlockBody ,
non-lexical-this , lex , privateEnv ) とする。
MakeMethod (bodyFunction ,
homeObject ) を実行する。
ClassStaticBlockDefinition
Record
{ [[BodyFunction]] : bodyFunction } を返す。
注
関数 bodyFunction は ECMAScript コードから直接アクセスされることはありません。
15.7.12 実行時意味論: EvaluateClassStaticBlockBody
構文指示操作
EvaluateClassStaticBlockBody は
引数 functionObject (ECMAScript 関数オブジェクト )を取り、
return completion または
throw completion
を返します。以下の生成規則ごとに部分的に定義されます:
ClassStaticBlockBody
: ClassStaticBlockStatementList
Assert :
functionObject は ClassStaticBlockDefinitionEvaluation
の 5 で作成された合成関数である。
! FunctionDeclarationInstantiation (functionObject ,
« ») を実行する。
? Evaluation (ClassStaticBlockStatementList
の)を実行する。
ReturnCompletion (undefined )
を返す。
15.7.13 実行時意味論: ClassElementEvaluation
構文指示操作
ClassElementEvaluation は
引数 object (オブジェクト)を取り、
正常完了(
ClassFieldDefinition
Record
、ClassStaticBlockDefinition
Record
、PrivateElement
または unused のいずれかを含む)または
異常完了
を返します。以下の生成規則ごとに部分的に定義されます:
ClassElement :
FieldDefinition
;
static
FieldDefinition
;
? ClassFieldDefinitionEvaluation (FieldDefinition の、引数
object )を返す。
ClassElement :
MethodDefinition
static
MethodDefinition
? MethodDefinitionEvaluation (MethodDefinition の、引数
object と false )を返す。
ClassElement : ClassStaticBlock
ClassStaticBlockDefinitionEvaluation
(ClassStaticBlock
の、引数 object )を返す。
ClassElement : ;
unused を返す。
15.7.14 実行時意味論: ClassDefinitionEvaluation
構文指示操作
ClassDefinitionEvaluation は
引数 classBinding (文字列または undefined )と className (プロパティキー または
Private
Name )を受け取り、
正常完了(
関数オブジェクト
を含む)または
異常完了
を返します。
注
仕様上の都合のため、プライベートメソッドとアクセサは、クラスインスタンスの [[PrivateElements]]
スロットにプライベートフィールドと一緒に含まれます。ただし、任意のオブジェクトは、あるクラスで定義されたすべてまたは全くプライベートメソッド・アクセサを持つことになります。この機能は、実装が各メソッドやアクセサを個別に追跡する必要のない戦略を選択できるよう設計されています。
例えば、実装はインスタンスプライベートメソッドを対応する Private Name に直接関連付け、各オブジェクトについてどのクラス
コンストラクター がそのオブジェクトを this
値として実行したかを追跡することができます。オブジェクト上でインスタンスプライベートメソッドを検索するには、そのメソッドを定義するクラス コンストラクター
がオブジェクトの初期化に使われたかを確認し、Private Name に関連付けられたメソッドを返すだけです。
これはプライベートフィールドとは異なります。なぜなら、フィールドイニシャライザーがクラスのインスタンス化中に例外を投げる可能性があるため、個々のオブジェクトはあるクラスのプライベートフィールドの部分集合しか持たない場合があり、したがってプライベートフィールドは一般に個別に追跡する必要があります。
以下の生成規則ごとに部分的に定義されます:
ClassTail :
ClassHeritage opt
{
ClassBody opt
}
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
classEnv を NewDeclarativeEnvironment (env )
とする。
classBinding が undefined でない場合、
! classEnv .CreateImmutableBinding(classBinding ,
true ) を実行する。
outerPrivateEnvironment を 実行中の実行コンテキスト の
PrivateEnvironment とする。
classPrivateEnvironment を NewPrivateEnvironment (outerPrivateEnvironment )
とする。
ClassBody が存在する場合、
ClassBody の
PrivateBoundIdentifiers
の各文字列 dn について、
classPrivateEnvironment .[[Names]] に、
dn を [[Description]] に持つ Private Name
pn が含まれている場合、
Assert :
これはゲッター/セッターのペアの場合のみ発生する。
それ以外の場合、
name を dn を [[Description]] に持つ新しい Private Name
とする。
name を classPrivateEnvironment .[[Names]] に追加する。
ClassHeritage
が存在しない場合、
protoParent を %Object.prototype%
とする。
constructorParent を %Function.prototype%
とする。
それ以外の場合、
実行中の実行コンテキスト の
LexicalEnvironment を classEnv に設定する。
注: 実行中の実行コンテキスト の
PrivateEnvironment は ClassHeritage の評価時は
outerPrivateEnvironment となる。
superclassRef を Completion (Evaluation (ClassHeritage )) とする。
実行中の実行コンテキスト の
LexicalEnvironment を env に設定する。
superclass を ? GetValue (?
superclassRef ) とする。
superclass が null の場合、
protoParent を null とする。
constructorParent を %Function.prototype%
とする。
それ以外で IsConstructor (superclass )
が false の場合、
TypeError 例外を投げる。
それ以外の場合、
protoParent を ? Get (superclass ,
"prototype" ) とする。
protoParent が オブジェクトでない
かつ protoParent が null
でない場合、TypeError 例外を投げる。
constructorParent を superclass とする。
proto を OrdinaryObjectCreate (protoParent )
とする。
ClassBody
が存在しない場合、constructor を empty とする。
それ以外の場合、constructor を ConstructorMethod (ClassBody の)とする。
実行中の実行コンテキスト の
LexicalEnvironment を classEnv に設定する。
実行中の実行コンテキスト の
PrivateEnvironment を classPrivateEnvironment に設定する。
constructor が empty の場合、
defaultConstructor を、パラメータなしで何もキャプチャせず、呼び出されたとき次の手順を実行する新しい Abstract Closure とする:
args を、この関数に [[Call]] または [[Construct]] で渡された引数の List
とする。
NewTarget が undefined
の場合、TypeError 例外を投げる。
F を アクティブな関数オブジェクト
とする。
F .[[ConstructorKind]] が
derived の場合、
注: この分岐は constructor(...args) { super(...args); }
と同様に振る舞う。ただし、上記 ECMAScript
ソーステキスト は %Array.prototype%
上の %Symbol.iterator%
メソッドを呼び出すが、この関数は呼び出さないという顕著な違いがある。
func を ! F .[[GetPrototypeOf]] () とする。
IsConstructor (func )
が false の場合、TypeError
例外を投げる。
result を ? Construct (func ,
args , NewTarget) とする。
それ以外の場合、
注: この分岐は constructor() {} と同様に振る舞う。
result を ? OrdinaryCreateFromConstructor (NewTarget,
"%Object.prototype%" ) とする。
? InitializeInstanceElements (result ,
F ) を実行する。
NormalCompletion (result )
を返す。
F を CreateBuiltinFunction (defaultConstructor ,
0, className , « [[ConstructorKind]] , [[SourceText]] », 現在の Realm Record ,
constructorParent ) とする。
それ以外の場合、
constructorInfo を ! DefineMethod (constructor 、引数
proto と constructorParent )とする。
F を constructorInfo .[[Closure]]
とする。
MakeClassConstructor (F )
を実行する。
SetFunctionName (F ,
className ) を実行する。
MakeConstructor (F ,
false , proto ) を実行する。
ClassHeritage
が存在する場合、F .[[ConstructorKind]] を
derived に設定する。
DefineMethodProperty (proto ,
"constructor" , F , false ) を実行する。
ClassBody
が存在しない場合、elements を新しい空の List とする。
それ以外の場合、elements を NonConstructorElements (ClassBody の)とする。
instancePrivateMethods を新しい空の List とする。
staticPrivateMethods を新しい空の List とする。
instanceFields を新しい空の List とする。
staticElements を新しい空の List とする。
elements の各 ClassElement e について、
IsStatic (e )
が false の場合、
element を Completion (ClassElementEvaluation (e ,
proto )) とする。
それ以外の場合、
element を Completion (ClassElementEvaluation (e ,
F )) とする。
element が 異常完了
の場合、
実行中の実行コンテキスト の
LexicalEnvironment を env に設定する。
実行中の実行コンテキスト の
PrivateEnvironment を outerPrivateEnvironment に設定する。
? element を返す。
element を ! element とする。
element が PrivateElement
の場合、
Assert : element .[[Kind]] は method または
accessor 。
IsStatic (e )
が false なら container を
instancePrivateMethods 、それ以外は staticPrivateMethods
とする。
container に element .[[Key]] と同じキーを持つ PrivateElement
pe が含まれている場合、
Assert :
element .[[Kind]] と
pe .[[Kind]] は両方
accessor 。
element .[[Get]] が
undefined の場合、
combined を PrivateElement
{ [[Key]] :
element .[[Key]] ,
[[Kind]] :
accessor , [[Get]] : pe .[[Get]] , [[Set]] : element .[[Set]] } とする。
それ以外の場合、
combined を PrivateElement
{ [[Key]] :
element .[[Key]] ,
[[Kind]] :
accessor , [[Get]] : element .[[Get]] , [[Set]] : pe .[[Set]] } とする。
container 内の pe を combined
で置換する。
それ以外の場合、
element を container に追加する。
それ以外で element が ClassFieldDefinition
Record の場合、
IsStatic (e )
が false なら instanceFields に、そうでなければ
staticElements に element を追加する。
それ以外で element が ClassStaticBlockDefinition
Record の場合、
element を staticElements に追加する。
実行中の実行コンテキスト の
LexicalEnvironment を env に設定する。
classBinding が undefined でない場合、
! classEnv .InitializeBinding(classBinding ,
F ) を実行する。
F .[[PrivateMethods]] を
instancePrivateMethods に設定する。
F .[[Fields]] を instanceFields に設定する。
staticPrivateMethods の各 PrivateElement
method について、
! PrivateMethodOrAccessorAdd (F ,
method ) を実行する。
staticElements の各 elementRecord について、
elementRecord が ClassFieldDefinition
Record の場合、
result を Completion (DefineField (F ,
elementRecord )) とする。
それ以外の場合、
Assert : elementRecord は
ClassStaticBlockDefinition
Record である。
result を Completion (Call (elementRecord .[[BodyFunction]] , F )) とする。
result が 異常完了
の場合、
実行中の実行コンテキスト の
PrivateEnvironment を outerPrivateEnvironment に設定する。
? result を返す。
実行中の実行コンテキスト の
PrivateEnvironment を outerPrivateEnvironment に設定する。
F を返す。
15.7.15 実行時意味論: BindingClassDeclarationEvaluation
構文指示操作
BindingClassDeclarationEvaluation は
引数を取らず、
正常完了(
関数オブジェクト
を含む)または
異常完了
を返します。以下の生成規則ごとに部分的に定義されます:
ClassDeclaration :
class
BindingIdentifier
ClassTail
className を BindingIdentifier の
StringValue とする。
value を ? ClassDefinitionEvaluation (ClassTail 、引数
className と className )とする。
value .[[SourceText]] を 一致したソーステキスト (ClassDeclaration )に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
? InitializeBoundName (className ,
value , env ) を実行する。
value を返す。
ClassDeclaration :
class
ClassTail
value を ? ClassDefinitionEvaluation (ClassTail 、引数
undefined と "default" )とする。
value .[[SourceText]] を 一致したソーステキスト (ClassDeclaration )に設定する。
value を返す。
注
ClassDeclaration
:
class
ClassTail
は ExportDeclaration
の一部としてのみ出現し、その束縛の確立はその生成規則の評価アクションで処理されます。16.2.3.7
を参照してください。
15.7.16 実行時意味論: 評価
ClassDeclaration :
class
BindingIdentifier
ClassTail
? BindingClassDeclarationEvaluation (この ClassDeclaration )を実行する。
empty を返す。
注
ClassExpression :
class
ClassTail
value を ? ClassDefinitionEvaluation (ClassTail 、引数
undefined と "" )とする。
value .[[SourceText]] を 一致したソーステキスト (ClassExpression )に設定する。
value を返す。
ClassExpression :
class
BindingIdentifier
ClassTail
className を BindingIdentifier の
StringValue とする。
value を ? ClassDefinitionEvaluation (ClassTail 、引数
className と className )とする。
value .[[SourceText]] を 一致したソーステキスト (ClassExpression )に設定する。
value を返す。
ClassElementName :
PrivateIdentifier
privateIdentifier を PrivateIdentifier の
StringValue とする。
privateEnvRec を 実行中の実行コンテキスト の
PrivateEnvironment とする。
names を privateEnvRec .[[Names]] とする。
Assert :
names のちょうど1つの要素が [[Description]] が
privateIdentifier である Private Name である。
privateName を names 内の [[Description]] が
privateIdentifier である Private Name とする。
privateName を返す。
ClassStaticBlockStatementList
: [empty]
undefined を返す。
15.8 非同期関数定義
構文
AsyncFunctionDeclaration [Yield,
Await, Default] :
async
[ここに LineTerminator はありません]
function
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
[+Default]
async
[ここに LineTerminator はありません]
function
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
[ここに LineTerminator はありません]
function
BindingIdentifier [~Yield,
+Await] opt
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncMethod [Yield,
Await] :
async
[ここに LineTerminator はありません]
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncFunctionBody :
FunctionBody [~Yield,
+Await]
AwaitExpression [Yield]
:
await
UnaryExpression [?Yield,
+Await]
注1
await は [Await] パラメータが存在する場合、AwaitExpression の キーワード として構文解析されます。
[Await] パラメータは、以下の文脈のトップレベルで存在しますが、非終端記号により一部の文脈(例えば FunctionBody )では欠如している場合もあります。
Script が構文 目標記号 の場合、await は
[Await] パラメータが存在しない時、識別子として構文解析されることがあります。これには以下の文脈が含まれます:
注2
YieldExpression
とは異なり、AwaitExpression
のオペランドを省略すると構文エラーとなります。必ず何かを await しなければなりません。
15.8.1 静的意味論: 早期エラー
AsyncMethod :
async
ClassElementName
(
UniqueFormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
15.8.2 実行時意味論: InstantiateAsyncFunctionObject
構文指示操作
InstantiateAsyncFunctionObject は
引数 env (Environment Record )および
privateEnv (PrivateEnvironment Record または
null )を受け取り、ECMAScript の 関数オブジェクト を返します。以下の生成規則ごとに部分的に定義されます:
AsyncFunctionDeclaration
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
name を BindingIdentifier の StringValue とする。
sourceText を 一致したソーステキスト (AsyncFunctionDeclaration )とする。
F を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , FormalParameters , AsyncFunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
name ) を実行する。
F を返す。
AsyncFunctionDeclaration
:
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
sourceText を 一致したソーステキスト (AsyncFunctionDeclaration )とする。
F を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , FormalParameters , AsyncFunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (F ,
"default" ) を実行する。
F を返す。
15.8.3 実行時意味論: InstantiateAsyncFunctionExpression
構文指示操作
InstantiateAsyncFunctionExpression は
オプション引数 name (プロパティキー または Private Name )を受け取り、ECMAScript の
関数オブジェクト を返します。以下の生成規則ごとに部分的に定義されます:
AsyncFunctionExpression
:
async
function
(
FormalParameters
)
{
AsyncFunctionBody
}
name が存在しなければ、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncFunctionExpression )とする。
closure を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , FormalParameters , AsyncFunctionBody ,
non-lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
closure を返す。
AsyncFunctionExpression
:
async
function
BindingIdentifier
(
FormalParameters
)
{
AsyncFunctionBody
}
Assert :
name は存在しない。
name を BindingIdentifier の StringValue に設定する。
outerEnv を 実行中の実行コンテキスト の
LexicalEnvironment とする。
funcEnv を NewDeclarativeEnvironment (outerEnv )
とする。
! funcEnv .CreateImmutableBinding(name ,
false ) を実行する。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncFunctionExpression )とする。
closure を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , FormalParameters , AsyncFunctionBody ,
non-lexical-this , funcEnv , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
! funcEnv .InitializeBinding(name , closure ) を実行する。
closure を返す。
注
15.8.4 実行時意味論: EvaluateAsyncFunctionBody
構文指示操作
EvaluateAsyncFunctionBody は
引数 functionObject (ECMAScript 関数オブジェクト )および argumentsList (ECMAScript 言語値 の リスト )を受け取り、
return completion
を返します。以下の生成規則ごとに部分的に定義されます:
AsyncFunctionBody
: FunctionBody
promiseCapability を ! NewPromiseCapability (%Promise% ) とする。
completion を Completion (FunctionDeclarationInstantiation (functionObject ,
argumentsList )) とする。
completion が 異常完了 の場合、
! Call (promiseCapability .[[Reject]] , undefined , «
completion .[[Value]] ») を実行する。
それ以外の場合、
AsyncFunctionStart (promiseCapability ,
FunctionBody )
を実行する。
ReturnCompletion (promiseCapability .[[Promise]] ) を返す。
15.8.5 実行時意味論: 評価
AsyncFunctionExpression
:
async
function
BindingIdentifier opt
(
FormalParameters
)
{
AsyncFunctionBody
}
InstantiateAsyncFunctionExpression
(AsyncFunctionExpression ) を返す。
AwaitExpression :
await
UnaryExpression
exprRef を ? Evaluation (UnaryExpression )とする。
value を ? GetValue (exprRef ) とする。
? Await (value ) を返す。
15.9 非同期アロー関数定義
構文
AsyncArrowFunction [In, Yield,
Await] :
async
[ここに LineTerminator はありません]
AsyncArrowBindingIdentifier [?Yield]
[ここに LineTerminator はありません]
=>
AsyncConciseBody [?In]
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
[ここに LineTerminator はありません]
=>
AsyncConciseBody [?In]
AsyncConciseBody [In]
:
[先読み ≠ { ]
ExpressionBody [?In,
+Await]
{
AsyncFunctionBody
}
AsyncArrowBindingIdentifier [Yield]
:
BindingIdentifier [?Yield,
+Await]
CoverCallExpressionAndAsyncArrowHead [Yield,
Await] :
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
補助構文
以下の生成規則インスタンスを処理する際
AsyncArrowFunction
:
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
の解釈は次の文法で洗練されます:
AsyncArrowHead :
async
[ここに LineTerminator はありません]
ArrowFormalParameters [~Yield,
+Await]
15.9.1 静的意味論: 早期エラー
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
AsyncArrowFunction
:
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
15.9.2 静的意味論: AsyncConciseBodyContainsUseStrict
構文指示操作
AsyncConciseBodyContainsUseStrict は
引数を取らず、Boolean を返します。以下の生成規則ごとに部分的に定義されます:
AsyncConciseBody :
ExpressionBody
false を返す。
AsyncConciseBody :
{
AsyncFunctionBody
}
FunctionBodyContainsUseStrict
(AsyncFunctionBody の)を返す。
15.9.3 実行時意味論: EvaluateAsyncConciseBody
構文指示操作
EvaluateAsyncConciseBody は
引数 functionObject (ECMAScript 関数オブジェクト )および argumentsList (ECMAScript 言語値 の リスト )を受け取り、
return completion
を返します。以下の生成規則ごとに部分的に定義されます:
AsyncConciseBody :
ExpressionBody
promiseCapability を ! NewPromiseCapability (%Promise% ) とする。
completion を Completion (FunctionDeclarationInstantiation (functionObject ,
argumentsList )) とする。
completion が 異常完了 の場合、
! Call (promiseCapability .[[Reject]] , undefined , «
completion .[[Value]] ») を実行する。
それ以外の場合、
AsyncFunctionStart (promiseCapability ,
ExpressionBody ) を実行する。
ReturnCompletion (promiseCapability .[[Promise]] ) を返す。
15.9.4 実行時意味論: InstantiateAsyncArrowFunctionExpression
構文指示操作
InstantiateAsyncArrowFunctionExpression は
オプション引数 name (プロパティキー または Private Name )を受け取り、ECMAScript の
関数オブジェクト を返します。以下の生成規則ごとに部分的に定義されます:
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
name が存在しなければ、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncArrowFunction )とする。
parameters を AsyncArrowBindingIdentifier
とする。
closure を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , parameters , AsyncConciseBody ,
lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
closure を返す。
AsyncArrowFunction
:
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
name が存在しなければ、name を "" に設定する。
env を 実行中の実行コンテキスト の
LexicalEnvironment とする。
privateEnv を 実行中の実行コンテキスト の
PrivateEnvironment とする。
sourceText を 一致したソーステキスト (AsyncArrowFunction )とする。
head を AsyncArrowHead (CoverCallExpressionAndAsyncArrowHead
で カバーされている もの)とする。
parameters を head の ArrowFormalParameters とする。
closure を OrdinaryFunctionCreate (%AsyncFunction.prototype% ,
sourceText , parameters , AsyncConciseBody ,
lexical-this , env , privateEnv ) とする。
SetFunctionName (closure ,
name ) を実行する。
closure を返す。
15.9.5 実行時意味論: 評価
AsyncArrowFunction
:
async
AsyncArrowBindingIdentifier
=>
AsyncConciseBody
CoverCallExpressionAndAsyncArrowHead
=>
AsyncConciseBody
InstantiateAsyncArrowFunctionExpression
(AsyncArrowFunction )を返す。
15.10 タイル位置呼び出し
15.10.1 静的セマンティクス: IsInTailPosition ( call )
抽象操作 IsInTailPosition は引数 call (CallExpression Parse
Node 、MemberExpression Parse
Node 、または OptionalChain Parse
Node )を取り、ブール値を返します。呼び出されたとき、次の手順を実行します:
IsStrict (call ) が
false の場合、false を返す。
call が FunctionBody 、ConciseBody 、または AsyncConciseBody
のいずれかに含まれていない場合、false を返す。
body を call を最も近く含んでいる FunctionBody 、ConciseBody 、または AsyncConciseBody とする。
body が FunctionBody の GeneratorBody
である場合、false を返す。
body が FunctionBody の AsyncFunctionBody
である場合、false を返す。
body が FunctionBody の AsyncGeneratorBody
である場合、false を返す。
body が AsyncConciseBody
である場合、false を返す。
HasCallInTailPosition
を body および引数 call で呼び出した結果を返す。
注
タイル位置呼び出しは 厳格モードコード
でのみ定義されている。これは、呼び出し元のコンテキストチェーンの観察を可能にする一般的な非標準言語拡張(10.2.4 参照)が存在するためである。
15.10.2 静的セマンティクス: HasCallInTailPosition
構文指示操作
HasCallInTailPosition は引数 call (CallExpression 構文ノード 、MemberExpression 構文ノード 、または OptionalChain 構文ノード )を取り、ブール値を返します。
注1
call は、ソーステキストの特定範囲を表す 構文ノード です。以下のアルゴリズムで
call と他の 構文ノード
を比較するときは、それらが同じソーステキストを表しているかどうかを判定します。
注2
呼び出し結果の return GetValue
が直後に続く潜在的なタイル位置呼び出しも、タイル位置呼び出しとなり得ます。関数呼び出しは Reference Record
を返すことはできないため、このような GetValue 操作は常に実際の関数呼び出しと同じ値を返します。
以下の生成規則に分割して定義されています:
StatementList :
StatementList
StatementListItem
has を HasCallInTailPosition
(StatementList 、引数
call )の結果とする。
has が true の場合、true を返す。
HasCallInTailPosition
(StatementListItem 、引数
call )の結果を返す。
FunctionStatementList
:
[empty]
StatementListItem
:
Declaration
Statement :
VariableStatement
EmptyStatement
ExpressionStatement
ContinueStatement
BreakStatement
ThrowStatement
DebuggerStatement
Block :
{
}
ReturnStatement :
return
;
LabelledItem :
FunctionDeclaration
ForInOfStatement :
for
(
LeftHandSideExpression
of
AssignmentExpression
)
Statement
for
(
var
ForBinding
of
AssignmentExpression
)
Statement
for
(
ForDeclaration
of
AssignmentExpression
)
Statement
CaseBlock :
{
}
false を返す。
IfStatement :
if
(
Expression
)
Statement
else
Statement
has を、最初の Statement および引数 call を使って
HasCallInTailPosition
の結果とする。
has が true の場合、true を返す。
2番目の Statement および引数
call を使って HasCallInTailPosition
の結果を返す。
IfStatement :
if
(
Expression
)
Statement
DoWhileStatement :
do
Statement
while
(
Expression
)
;
WhileStatement :
while
(
Expression
)
Statement
ForStatement :
for
(
Expression opt
;
Expression opt
;
Expression opt
)
Statement
for
(
var
VariableDeclarationList
;
Expression opt
;
Expression opt
)
Statement
for
(
LexicalDeclaration
Expression opt
;
Expression opt
)
Statement
ForInOfStatement :
for
(
LeftHandSideExpression
in
Expression
)
Statement
for
(
var
ForBinding
in
Expression
)
Statement
for
(
ForDeclaration
in
Expression
)
Statement
WithStatement :
with
(
Expression
)
Statement
HasCallInTailPosition
を Statement および引数
call で呼び出した結果を返す。
LabelledStatement
:
LabelIdentifier
:
LabelledItem
HasCallInTailPosition
を LabelledItem および引数
call で呼び出した結果を返す。
ReturnStatement :
return
Expression
;
HasCallInTailPosition
を Expression および引数
call で呼び出した結果を返す。
SwitchStatement :
switch
(
Expression
)
CaseBlock
HasCallInTailPosition
を CaseBlock および引数
call で呼び出した結果を返す。
CaseBlock :
{
CaseClauses opt
DefaultClause
CaseClauses opt
}
has を false とする。
最初の CaseClauses
が存在する場合、has を最初の CaseClauses および引数 call で
HasCallInTailPosition
を呼び出した結果とする。
has が true の場合、true を返す。
has を DefaultClause および引数 call で
HasCallInTailPosition
を呼び出した結果とする。
has が true の場合、true を返す。
2番目の CaseClauses
が存在する場合、has を2番目の CaseClauses および引数 call で
HasCallInTailPosition
を呼び出した結果とする。
has を返す。
CaseClauses :
CaseClauses
CaseClause
has を CaseClauses および引数 call で
HasCallInTailPosition
を呼び出した結果とする。
has が true の場合、true を返す。
HasCallInTailPosition
を CaseClause および引数
call で呼び出した結果を返す。
CaseClause :
case
Expression
:
StatementList opt
DefaultClause :
default
:
StatementList opt
StatementList
が存在する場合、HasCallInTailPosition
を StatementList および引数
call で呼び出した結果を返す。
false を返す。
TryStatement :
try
Block
Catch
HasCallInTailPosition
を Catch および引数 call
で呼び出した結果を返す。
TryStatement :
try
Block
Finally
try
Block
Catch
Finally
HasCallInTailPosition
を Finally および引数
call で呼び出した結果を返す。
Catch :
catch
(
CatchParameter
)
Block
HasCallInTailPosition
を Block および引数 call
で呼び出した結果を返す。
AssignmentExpression
:
YieldExpression
ArrowFunction
AsyncArrowFunction
LeftHandSideExpression
=
AssignmentExpression
LeftHandSideExpression
AssignmentOperator
AssignmentExpression
LeftHandSideExpression
&&=
AssignmentExpression
LeftHandSideExpression
||=
AssignmentExpression
LeftHandSideExpression
??=
AssignmentExpression
BitwiseANDExpression
:
BitwiseANDExpression
&
EqualityExpression
BitwiseXORExpression
:
BitwiseXORExpression
^
BitwiseANDExpression
BitwiseORExpression
:
BitwiseORExpression
|
BitwiseXORExpression
EqualityExpression
:
EqualityExpression
==
RelationalExpression
EqualityExpression
!=
RelationalExpression
EqualityExpression
===
RelationalExpression
EqualityExpression
!==
RelationalExpression
RelationalExpression
:
RelationalExpression
<
ShiftExpression
RelationalExpression
>
ShiftExpression
RelationalExpression
<=
ShiftExpression
RelationalExpression
>=
ShiftExpression
RelationalExpression
instanceof
ShiftExpression
RelationalExpression
in
ShiftExpression
PrivateIdentifier
in
ShiftExpression
ShiftExpression :
ShiftExpression
<<
AdditiveExpression
ShiftExpression
>>
AdditiveExpression
ShiftExpression
>>>
AdditiveExpression
AdditiveExpression
:
AdditiveExpression
+
MultiplicativeExpression
AdditiveExpression
-
MultiplicativeExpression
MultiplicativeExpression
:
MultiplicativeExpression
MultiplicativeOperator
ExponentiationExpression
ExponentiationExpression
:
UpdateExpression
**
ExponentiationExpression
UpdateExpression :
LeftHandSideExpression
++
LeftHandSideExpression
--
++
UnaryExpression
--
UnaryExpression
UnaryExpression :
delete
UnaryExpression
void
UnaryExpression
typeof
UnaryExpression
+
UnaryExpression
-
UnaryExpression
~
UnaryExpression
!
UnaryExpression
AwaitExpression
CallExpression :
SuperCall
ImportCall
CallExpression
[
Expression
]
CallExpression
.
IdentifierName
CallExpression
.
PrivateIdentifier
NewExpression :
new
NewExpression
MemberExpression :
MemberExpression
[
Expression
]
MemberExpression
.
IdentifierName
SuperProperty
MetaProperty
new
MemberExpression
Arguments
MemberExpression
.
PrivateIdentifier
PrimaryExpression
:
this
IdentifierReference
Literal
ArrayLiteral
ObjectLiteral
FunctionExpression
ClassExpression
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral
false を返す。
Expression :
AssignmentExpression
Expression
,
AssignmentExpression
HasCallInTailPosition
を AssignmentExpression および引数
call で呼び出した結果を返す。
ConditionalExpression
:
ShortCircuitExpression
?
AssignmentExpression
:
AssignmentExpression
has を最初の AssignmentExpression および引数
call で HasCallInTailPosition
を呼び出した結果とする。
has が true の場合、true を返す。
2番目の AssignmentExpression および引数
call で HasCallInTailPosition
を呼び出した結果を返す。
LogicalANDExpression
:
LogicalANDExpression
&&
BitwiseORExpression
HasCallInTailPosition
を BitwiseORExpression および引数
call で呼び出した結果を返す。
LogicalORExpression
:
LogicalORExpression
||
LogicalANDExpression
HasCallInTailPosition
を LogicalANDExpression および引数
call で呼び出した結果を返す。
CoalesceExpression
:
CoalesceExpressionHead
??
BitwiseORExpression
HasCallInTailPosition
を BitwiseORExpression および引数
call で呼び出した結果を返す。
CallExpression :
CoverCallExpressionAndAsyncArrowHead
CallExpression
Arguments
CallExpression
TemplateLiteral
この CallExpression が
call である場合、true を返す。
false を返す。
OptionalExpression
:
MemberExpression
OptionalChain
CallExpression
OptionalChain
OptionalExpression
OptionalChain
HasCallInTailPosition
を OptionalChain および引数
call で呼び出した結果を返す。
OptionalChain :
?.
[
Expression
]
?.
IdentifierName
?.
PrivateIdentifier
OptionalChain
[
Expression
]
OptionalChain
.
IdentifierName
OptionalChain
.
PrivateIdentifier
false を返す。
OptionalChain :
?.
Arguments
OptionalChain
Arguments
この OptionalChain
が call である場合、true を返す。
false を返す。
MemberExpression :
MemberExpression
TemplateLiteral
この MemberExpression が call
である場合、true を返す。
false を返す。
PrimaryExpression
: CoverParenthesizedExpressionAndArrowParameterList
expr を ParenthesizedExpression
であり、CoverParenthesizedExpressionAndArrowParameterList
によって カバーされている ものとする。
HasCallInTailPosition
を expr および引数 call で呼び出した結果を返す。
ParenthesizedExpression
:
(
Expression
)
HasCallInTailPosition
を Expression および引数
call で呼び出した結果を返す。
15.10.3 PrepareForTailCall ( )
抽象操作 PrepareForTailCall は引数を取らず、unused を返す。呼び出されたとき、次の手順を実行する:
Assert : 現在の
execution context は、その後 ECMAScript
コードや組み込み関数の評価には使用されない。 この抽象操作の呼び出し後に Call が呼び出された場合、評価の前に新しい execution context が作成・プッシュされる。
現在の execution context
に関連するすべてのリソースを破棄する。
unused を返す。
タイル位置呼び出しは、ターゲット関数の呼び出し前に現在実行中の関数 execution context
に関連する一時的な内部リソースを解放するか、それらのリソースをターゲット関数のために再利用しなければならない。
注
例えば、タイル位置呼び出しでは、ターゲット関数のアクティベーションレコードのサイズが呼び出し元関数のそれを超える分だけ、実装のアクティベーションレコードスタックが増加すべきである。ターゲット関数のアクティベーションレコードが小さい場合、スタックの合計サイズは減少するはずである。
16 ECMAScript言語:スクリプトとモジュール
16.1 スクリプト
構文
Script :
ScriptBody opt
ScriptBody :
StatementList [~Yield, ~Await,
~Return]
16.1.1 静的セマンティクス:早期エラー
Script : ScriptBody
ScriptBody : StatementList
16.1.2 静的セマンティクス:ScriptIsStrict
構文指示操作
ScriptIsStrict は引数を取らず、ブール値を返す。以下の生成規則に分割して定義される:
Script : ScriptBody opt
ScriptBody が存在し、かつその
Directive Prologue に Use
Strict Directive が含まれる場合、true を返す。そうでなければ
false を返す。
16.1.3 実行時セマンティクス:評価
Script : [empty]
undefined を返す。
16.1.4 スクリプトレコード
スクリプトレコード は評価されるスクリプトに関する情報をカプセル化する。各スクリプトレコードは 表39 に記載されているフィールドを含む。
表39: スクリプトレコード のフィールド
16.1.5 ParseScript ( sourceText , realm ,
hostDefined )
抽象操作 ParseScript は引数 sourceText (ECMAScriptソーステキスト )、 realm (Realm Record )、
hostDefined (任意)を取り、 スクリプトレコード または空でない List (SyntaxError
オブジェクトのリスト)を返す。 sourceText を Script としてパースした結果に基づき スクリプトレコード を作成する。呼び出されたとき、以下の手順を実行する:
script を ParseText (sourceText , Script ) の結果とする。
script がエラーの List
である場合、 script を返す。
スクリプトレコード { [[Realm]] : realm ,
[[ECMAScriptCode]] : script , [[LoadedModules]] : « », [[HostDefined]] : hostDefined } を返す。
注
実装は、スクリプトソーステキストをパースし、ParseScriptの評価前に早期エラー条件を分析してもよい。ただし、エラーの報告はこの仕様が実際にそのソーステキストにParseScriptを実行する時点まで遅延しなければならない。
16.1.6 ScriptEvaluation ( scriptRecord )
抽象操作 ScriptEvaluation は引数 scriptRecord (スクリプトレコード )を取り、 通常の完了(normal
completion) (ECMAScript言語値 を含む)または
突然の完了(abrupt completion)
のいずれかを返す。呼び出されたとき、以下の手順を実行する:
globalEnv を scriptRecord .[[Realm]] .[[GlobalEnv]] とする。
scriptContext を新しい ECMAScriptコード実行コンテキスト
とする。
scriptContext のFunctionを null に設定する。
scriptContext の Realm を scriptRecord .[[Realm]] に設定する。
scriptContext のScriptOrModuleを scriptRecord に設定する。
scriptContext のVariableEnvironmentを globalEnv に設定する。
scriptContext のLexicalEnvironmentを globalEnv に設定する。
scriptContext のPrivateEnvironmentを null に設定する。
実行中の実行コンテキスト を中断する(Suspend)。
scriptContext を 実行コンテキストスタック
にプッシュする。scriptContext が新たな 実行中の実行コンテキスト となる。
script を scriptRecord .[[ECMAScriptCode]]
とする。
result を Completion (GlobalDeclarationInstantiation (script ,
globalEnv )) の結果とする。
result が 通常の完了 である場合、
result を Completion (Evaluation (script ))
の結果とする。
result が 通常の完了
であり、 result .[[Value]] が
empty の場合、
result を NormalCompletion (undefined )
の結果とする。
scriptContext を中断し、 実行コンテキストスタック
から削除する。
Assert :
実行コンテキストスタック が空でないことを確認する。
実行コンテキストスタック の現在トップにあるコンテキストを
実行中の実行コンテキスト として再開する(Resume)。
? result を返す。
16.1.7 GlobalDeclarationInstantiation ( script ,
env )
抽象操作 GlobalDeclarationInstantiation は引数 script (Script 構文ノード )、
env (グローバル環境レコード )を取り、 通常の完了(unused
を含む) または throw
completion を返す。 script は 実行コンテキスト を確立するための Script であり、 env
はバインディングを作成するためのグローバル環境である。
注1
スクリプト評価のために 実行コンテキスト
が確立されると、宣言は現在のグローバル環境でインスタンス化される。コード内で宣言された各グローバルバインディングはインスタンス化される。
呼び出されたとき、以下の手順を実行する:
lexNames を script の LexicallyDeclaredNames
の結果とする。
varNames を script の VarDeclaredNames
の結果とする。
lexNames の各 name について、以下を実行する:
HasLexicalDeclaration (env ,
name ) が true の場合、 SyntaxError
例外をthrowする。
hasRestrictedGlobal を ? HasRestrictedGlobalProperty (env ,
name ) の結果とする。
注:グローバル var および function バインディング(非厳格 直接eval
で導入されたものを除く)は、設定不可(non-configurable)であり、したがって制限付きグローバルプロパティとなる。
hasRestrictedGlobal が true の場合、
SyntaxError 例外をthrowする。
varNames の各 name について、以下を実行する:
HasLexicalDeclaration (env ,
name ) が true の場合、 SyntaxError
例外をthrowする。
varDeclarations を script の VarScopedDeclarations
の結果とする。
functionsToInitialize を新しい空の List とする。
declaredFunctionNames を新しい空の List とする。
varDeclarations の各 d について、逆順で以下を実行する:
d が VariableDeclaration 、
ForBinding 、
BindingIdentifier
のいずれでもない場合、以下を実行する:
Assert : d は FunctionDeclaration 、
GeneratorDeclaration 、
AsyncFunctionDeclaration 、または
AsyncGeneratorDeclaration
のいずれかである。
注:同じ名前の関数宣言が複数ある場合、最後の宣言が使用される。
fn を d の BoundNames
の唯一の要素とする。
declaredFunctionNames に fn が含まれていない場合、以下を実行する:
fnDefinable を ? CanDeclareGlobalFunction (env ,
fn ) の結果とする。
fnDefinable が false の場合、
TypeError 例外をthrowする。
fn を declaredFunctionNames に追加する。
d を functionsToInitialize の先頭に挿入する。
declaredVarNames を新しい空の List とする。
varDeclarations の各 d について、以下を実行する:
d が VariableDeclaration 、
ForBinding 、
BindingIdentifier
のいずれかである場合、以下を実行する:
d の BoundNames
の各文字列 vn について、以下を実行する:
declaredFunctionNames に vn
が含まれていない場合、以下を実行する:
vnDefinable を ? CanDeclareGlobalVar (env ,
vn ) の結果とする。
vnDefinable が false の場合、
TypeError 例外をthrowする。
declaredVarNames に vn
が含まれていない場合、以下を実行する:
vn を declaredVarNames
に追加する。
注:グローバルオブジェクトが 通常のオブジェクト
の場合、このアルゴリズムステップ以降は異常終了は発生しない。ただし、グローバルオブジェクトが Proxyエキゾチックオブジェクト
の場合、以下のいくつかのステップで異常終了が発生することがある。
注:付録 B.3.2.2
でこのポイントに追加のステップが挿入される。
lexDeclarations を script の LexicallyScopedDeclarations
の結果とする。
privateEnv を null とする。
lexDeclarations の各 d について、以下を実行する:
注:レキシカル宣言名はここでインスタンス化されるが、初期化はされない。
d の BoundNames の各
dn について、以下を実行する:
IsConstantDeclaration
の結果が true であれば、以下を実行する:
? env .CreateImmutableBinding (dn ,
true ) を行う。
そうでなければ、以下を実行する:
? env .CreateMutableBinding (dn ,
false ) を行う。
functionsToInitialize の各 構文ノード f
について、以下を実行する:
fn を f の BoundNames
の唯一の要素とする。
fo を InstantiateFunctionObject (f ,
env , privateEnv ) の結果とする。
? CreateGlobalFunctionBinding (env ,
fn , fo , false ) を行う。
declaredVarNames の各文字列 vn について、以下を実行する:
? CreateGlobalVarBinding (env ,
vn , false ) を行う。
unused を返す。
注2
早期エラー (16.1.1 で定義)は、関数/var宣言とlet/const/class宣言の名前の競合や、同一Script内でのlet/const/classバインディングの再宣言を防ぐ。ただし、複数のScriptにまたがる競合や再宣言は、GlobalDeclarationInstantiation
の実行時エラーとして検出される。これらのエラーが検出された場合、そのスクリプトのバインディングはインスタンス化されない。ただし、グローバルオブジェクトが Proxyエキゾチックオブジェクト
で定義される場合、競合宣言の検出は信頼できず、突然の完了 となり、一部のグローバル宣言がインスタンス化されないことがある。この場合、Scriptのコードは評価されない。
明示的なvarやfunction宣言とは異なり、グローバルオブジェクト上に直接作成されたプロパティは、let/const/class宣言によってシャドウされるグローバルバインディングとなる場合がある。
16.2 モジュール
構文
Module :
ModuleBody opt
ModuleBody :
ModuleItemList
ModuleItemList :
ModuleItem
ModuleItemList
ModuleItem
ModuleItem :
ImportDeclaration
ExportDeclaration
StatementListItem [~Yield,
+Await, ~Return]
ModuleExportName :
IdentifierName
StringLiteral
16.2.1 モジュールのセマンティクス
16.2.1.1 静的セマンティクス:早期エラー
ModuleBody : ModuleItemList
注
ExportedNames
の重複エラー規則は、ModuleBody
内に export default ExportDeclaration
が複数存在する場合に構文エラーとなることを意味する。競合や重複宣言に関する追加のエラー条件は、 Module
の評価前のモジュールリンク時にチェックされる。これらのエラーが検出されると、 Module は評価されない。
ModuleExportName
: StringLiteral
16.2.1.2 静的セマンティクス: ImportedLocalNames (
importEntries )
抽象操作 ImportedLocalNames は、引数 importEntries (List (ImportEntry
Record のリスト))を取り、文字列の List を返す。これは
importEntries により定義されたすべてのローカル名バインディングのリストを作成する。呼び出されたとき、次の手順を実行する:
localNames を新しい空の List とする。
importEntries の各 ImportEntry Record i
について、以下を実行する:
i .[[LocalName]] を localNames
に追加する。
localNames を返す。
16.2.1.3 ModuleRequest レコード
ModuleRequest
Record は、指定された import 属性を持つモジュールの import 要求を表す。次のフィールドを持つ:
表40: ModuleRequest Record のフィールド
LoadedModuleRequest Record は、モジュールの import 要求と、その import 要求に対応する
Module Record を表す。表 40 で定義されたフィールドに加え、 [[Module]] フィールドが追加される:
表41: LoadedModuleRequest Record
のフィールド
ImportAttribute Record は、次のフィールドを持つ:
表42: ImportAttribute Record のフィールド
フィールド名
値の型
意味
[[Key]]
文字列
属性のキー
[[Value]]
文字列
属性の値
16.2.1.3.1 ModuleRequestsEqual ( left ,
right )
抽象操作 ModuleRequestsEqual は、引数 left (ModuleRequest Record
または LoadedModuleRequest Record )と
right (ModuleRequest Record または LoadedModuleRequest
Record )を取り、ブール値を返す。呼び出されたとき、次の手順を実行する:
left .[[Specifier]] が right .[[Specifier]] と異なる場合、false を返す。
leftAttrs を left .[[Attributes]]
とする。
rightAttrs を right .[[Attributes]]
とする。
leftAttrsCount を leftAttrs の要素数とする。
rightAttrsCount を rightAttrs の要素数とする。
leftAttrsCount ≠ rightAttrsCount
の場合、false を返す。
leftAttrs の各 ImportAttribute
Record l について、以下を実行する:
rightAttrs に l .[[Key]] が
r .[[Key]] であり、かつ l .[[Value]] が r .[[Value]] である ImportAttribute
Record r
が含まれていない場合、false を返す。
true を返す。
16.2.1.4 静的セマンティクス:ModuleRequests
構文指示操作
ModuleRequests は引数を取らず、List (ModuleRequest
Record のリスト)を返す。以下の生成規則ごとに定義される:
Module : [empty]
List
の新しい空リストを返す。
ModuleItemList :
ModuleItem
ModuleItem の
ModuleRequests
を返す。
ModuleItemList :
ModuleItemList
ModuleItem
requests を ModuleItemList の ModuleRequests
の結果とする。
additionalRequests を ModuleItem の ModuleRequests
の結果とする。
additionalRequests の各 ModuleRequest
Record
mr について、以下を実行する:
requests に mr2 (ModuleRequest
Record )で ModuleRequestsEqual (mr ,
mr2 ) が true となるものが含まれていない場合、以下を実行:
mr を requests に追加する。
requests を返す。
ModuleItem : StatementListItem
List
の新しい空リストを返す。
ImportDeclaration
:
import
ImportClause
FromClause
;
specifier を FromClause の SV の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » } を持つ List を返す。
ImportDeclaration
:
import
ImportClause
FromClause
WithClause
;
specifier を FromClause の SV の結果とする。
attributes を WithClause の WithClauseToAttributes
の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attributes } を持つ List を返す。
ImportDeclaration
:
import
ModuleSpecifier
;
specifier を ModuleSpecifier の SV
の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » } を持つ List を返す。
ImportDeclaration
:
import
ModuleSpecifier
WithClause
;
specifier を ModuleSpecifier の SV
の結果とする。
attributes を WithClause の WithClauseToAttributes
の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attributes } を持つ List を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
;
specifier を FromClause の SV の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : « » } を持つ List を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause
;
specifier を FromClause の SV の結果とする。
attributes を WithClause の WithClauseToAttributes
の結果とする。
唯一の要素として ModuleRequest Record { [[Specifier]] : specifier , [[Attributes]] : attributes } を持つ List を返す。
ExportDeclaration
:
export
NamedExports
;
export
VariableStatement
export
Declaration
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
List
の新しい空リストを返す。
16.2.1.5 抽象モジュールレコード
モジュールレコード は、単一のモジュールのインポートおよびエクスポートに関する構造的情報をカプセル化する。この情報は、接続されたモジュール群のインポートとエクスポートをリンクするために使用される。モジュールレコードには、モジュールの評価時のみ使用される4つのフィールドが含まれる。
仕様上、モジュールレコード値は Record
仕様型の値であり、単純なオブジェクト指向階層に存在するとみなすことができる。Module
Recordは抽象クラスであり、抽象サブクラスと具体サブクラスがある。この仕様では、抽象サブクラス Cyclic Module Record
と、その具体サブクラス Source Text Module Record
を定義する。他の仕様や実装では、定義した代替モジュール定義機能に応じたモジュールレコードのサブクラスを追加できる。
Module Recordは 表43
に記載のフィールドを定義する。すべてのモジュール定義サブクラスは少なくともそれらのフィールドを含む。Module Recordはまた、表44
に示す抽象メソッドリストを定義する。すべてのモジュール定義サブクラスはこれら抽象メソッドの具体的な実装を提供しなければならない。
表43: モジュールレコード のフィールド
表44: モジュールレコード の抽象メソッド
メソッド
目的
LoadRequestedModules([hostDefined ])
モジュールをリンクするために、依存関係を再帰的に読み込み、Promiseを返す。
GetExportedNames([exportStarSet ])
このモジュールから直接または間接的にエクスポートされるすべての名前のリストを返す。
このメソッドを呼び出す前に LoadRequestedModules が正常に完了している必要がある。
ResolveExport(exportName [, resolveSet ])
このモジュールによってエクスポートされた名前のバインディングを返す。バインディングは ResolvedBinding
Record ({ [[Module]] :
Module
Record , [[BindingName]] : String |
namespace
})で表現される。エクスポートがモジュール名前空間オブジェクトで直接バインディングを持たない場合は [[BindingName]] に
namespace が設定される。名前が解決できなければ
null 、複数バインディングが見つかった場合は
ambiguous を返す。
この操作は、特定の exportName と resolveSet
の組み合わせで呼び出された際、同じ結果を返さなければならない。
このメソッドを呼び出す前に LoadRequestedModules が正常に完了している必要がある。
Link()
モジュールを評価する準備として、すべての依存関係を推移的に解決し、Module Environment
Record を作成する。
このメソッドを呼び出す前に LoadRequestedModules が正常に完了している必要がある。
Evaluate()
このモジュールと依存関係の評価のPromiseを返す。評価が成功するか、すでに成功していればresolveされ、評価エラーが発生するか、すでに失敗していればrejectされる。Promiseがrejectされた場合、ホスト はPromiseのrejectを処理し、評価エラーを再throwすることが期待される。
このメソッドを呼び出す前に Link が正常に完了している必要がある。
16.2.1.5.1 EvaluateModuleSync ( module )
抽象操作 EvaluateModuleSync は module (Module
Record )を引数に取り、 通常の完了(unused を含む)
または throw completion
を返す。呼び出し側が module の評価がすでにsettled状態のPromiseを返すことを保証する場合に、同期的に
module を評価する。呼び出されたとき、以下の手順を実行する:
Assert :
module は Cyclic Module Record ではない。
promise を module .Evaluate() の結果とする。
Assert :
promise .[[PromiseState]] は
fulfilled または rejected のいずれかである。
promise .[[PromiseState]] が
rejected の場合、以下を実行する:
promise .[[PromiseIsHandled]] が
false の場合、 HostPromiseRejectionTracker (promise ,
"handle" ) を実行する。
promise .[[PromiseIsHandled]] を
true に設定する。
ThrowCompletion (promise .[[PromiseResult]] ) を返す。
unused を返す。
16.2.1.6 순환 모듈 레코드
순환 모듈
레코드 는 Cyclic Module Record 타입의 다른 모듈들과의 의존성
사이클에 참여할 수 있는 모듈에 대한 정보를 나타내는 데 사용됩니다. Module Records 가
Cyclic
Module Record 타입의 하위 클래스가 아닌 경우 Source
Text Module Records 와의 의존성 사이클에 참여해서는 안 됩니다.
표 43 에 정의된 필드들 외에도 Cyclic
Module Records 는 표 45 에 나열된 추가 필드들을
가집니다.
표 45: 순환 모듈 레코드 의 추가 필드
필드 이름
값 타입
의미
[[Status]]
new , unlinked ,
linking , linked ,
evaluating ,
evaluating-async , 또는
evaluated
처음에는 new 입니다. 모듈의 생애 주기 동안
unlinked , linking ,
linked , evaluating , 경우에 따라
evaluating-async ,
evaluated 로(그 순서로) 전이됩니다.
evaluating-async 는 이 모듈이 비동기 의존성이 완료된 후 실행 대기 중이거나
[[HasTLA]] 필드가 true 인 모듈로서
실행되었고, 최상위 완료를 대기 중임을 나타냅니다.
[[EvaluationError]]
throw
completion 또는 empty
평가 중 발생한 예외를 나타내는 throw
completion 입니다. 예외가 발생하지 않았거나 [[Status]] 가 evaluated 가
아니면 undefined 입니다.
[[DFSAncestorIndex]]
integer 또는
empty
Link 및 Evaluate 중에만 사용하는 보조 필드입니다. [[Status]] 가
linking 또는 evaluating 일 때,
이 값은 모듈의 깊이 우선 탐색 인덱스이거나 동일한 강하게 연결된 구성 요소 내의 "이전" 모듈의 인덱스입니다.
[[RequestedModules]]
List
of ModuleRequest
Records
이 모듈의 import와 연관된 ModuleRequest
Records 의 List 입니다.
import의 소스 텍스트 발생 순서대로 리스트가 정렬됩니다.
[[LoadedModules]]
List
of LoadedModuleRequest
Records
이 레코드가 나타내는 모듈이 상대적 import 속성을 가지고 모듈을 import 요청할 때 사용한 specifier 문자열에서
Module
Record 로 매핑되는 정보입니다. 리스트에는 Records
r1 과 r2 가 존재하지 않습니다. ModuleRequestsEqual (r1 ,
r2 )가 true 인 경우.
[[CycleRoot]]
Cyclic Module Record
또는 empty
사이클 내에서 처음 방문한 모듈, 강하게 연결된 구성 요소의 루트 DFS 조상입니다. 사이클에 속하지 않은 모듈의 경우 자신이
됩니다. Evaluate가 완료된 후, 모듈의 [[DFSAncestorIndex]] 는
[[CycleRoot]] 의 깊이 우선 탐색 인덱스가 됩니다.
[[HasTLA]]
Boolean
이 모듈이 개별적으로 비동기적인지 여부(예: 최상위 await가 포함된 Source Text Module
Record 일 경우). 비동기 의존성이 있다고 해서 이 필드가
true 가 되는 것은 아닙니다. 이 필드는 모듈이 파싱된 이후에 변경되면 안 됩니다.
[[AsyncEvaluationOrder]]
unset , integer , 또는
done
이 필드는 처음에 unset 으로 설정되며, 완전히 동기적인 모듈의 경우 계속
unset 입니다. 모듈 자체가 비동기이거나 비동기 의존성을 가진 경우, integer 로 설정되어 16.2.1.6.1.3.4 에
의해 대기 중인 모듈 실행 순서를 결정합니다. 대기 모듈이 실행되면 done 으로
설정됩니다.
[[TopLevelCapability]]
PromiseCapability
Record 또는 empty
이 모듈이 어떤 사이클의 [[CycleRoot]] 이고, 그 사이클의 모듈 중 하나에
대해 Evaluate()가 호출된 경우, 이 필드는 전체 평가에 대한 PromiseCapability
Record 를 포함합니다. 이는 Evaluate() 추상 메서드에서 반환되는
Promise 객체를 해결하는 데 사용됩니다. 해당 모듈의 의존성에는 empty 가 되며,
일부 의존성에 대해 최상위 Evaluate()가 시작된 경우를 제외합니다.
[[AsyncParentModules]]
List
of Cyclic Module
Records
이 모듈 또는 의존성이 [[HasTLA]]
true 이고, 실행이 진행 중이라면, 이 필드는 최상위 실행 작업에 대한 이 모듈의 부모
importers를 추적합니다. 이 부모 모듈들은 이 모듈이 성공적으로 실행 완료되기 전까지는 실행을 시작하지 않습니다.
[[PendingAsyncDependencies]]
integer 또는
empty
이 모듈에 비동기 의존성이 있으면, 이 필드는 해당 모듈이 실행될 때까지 남은 비동기 의존성 모듈의 수를 추적합니다. 비동기
의존성이 있는 모듈은 이 값이 0이 되고 실행 오류가 없을 때 실행됩니다.
표 44 에 정의된 메서드들 외에도
순환 모듈
레코드 는 표 46 에 나열된 추가 메서드들을 가집니다.
표 46: 순환 모듈 레코드 의 추가 추상 메서드
GraphLoadingState 레코드 는 모듈 그래프의 로딩 과정에 대한 정보를 담고 있는 Record 입니다. 이는
HostLoadImportedModule 호출 이후 로딩을
계속하기 위해 사용됩니다. 각 GraphLoadingState 레코드 는 표 47 에 정의된 필드들을 가집니다:
표 47: GraphLoadingState 레코드 의 필드
16.2.1.6.1 モジュールレコード抽象メソッドの実装
以下は、循環モジュールレコード に対応する モジュールレコード
抽象メソッドを実装する具体的なメソッドです。これらの抽象メソッドは 表44 で定義されています。
16.2.1.6.1.1 LoadRequestedModules (
[hostDefined ] )
循環モジュールレコード module の
LoadRequestedModules 具体メソッドは、オプション引数 hostDefined (任意型)を受け取り、Promise
を返します。このメソッドは module の依存グラフ内のすべての モジュールレコード の [[LoadedModules]] を埋めます(大部分の処理は補助関数 InnerModuleLoading
によって行われます)。オプションの hostDefined パラメータは HostLoadImportedModule
フックに渡されます。呼び出されると以下の手順を実行します:
もし hostDefined が存在しなければ、hostDefined を
empty とする。
pc を ! NewPromiseCapability (%Promise% ) とする。
state を GraphLoadingState
レコード { [[IsLoading]] :
true , [[PendingModulesCount]] :
1, [[Visited]] : « », [[PromiseCapability]] : pc , [[HostDefined]] : hostDefined } とする。
InnerModuleLoading (state ,
module ) を実行する。
pc .[[Promise]] を返す。
注
hostDefined パラメータは、import
されたモジュールを取得するために必要な追加情報を渡すために使用できます。例えば、HTML では
<link rel="preload" as="..."> タグにおいて、正しい fetch destination
を設定するために利用されます。
import() 式では hostDefined パラメータは決して設定されません。
16.2.1.6.1.1.1 InnerModuleLoading (state ,
module )
抽象操作 InnerModuleLoading は、引数 state (GraphLoadingState
レコード )および module (モジュールレコード )を受け取り、unused
を返します。これは LoadRequestedModules から呼び出され、module
の依存グラフに対する実際のロード処理を再帰的に行うために使われます。呼び出されると以下の手順を実行します:
アサート : state .[[IsLoading]] は true である。
もし module が 循環モジュールレコード
であり、module .[[Status]] が
new で、かつ state .[[Visited]] に module が含まれていなければ、次を行う:
module を state .[[Visited]] に追加する。
requestedModulesCount を module .[[RequestedModules]] の要素数とする。
state .[[PendingModulesCount]] を
state .[[PendingModulesCount]] +
requestedModulesCount に設定する。
各 ModuleRequest
レコード request
について、module .[[RequestedModules]] の中で次を行う:
もし AllImportAttributesSupported (request .[[Attributes]] ) が
false なら、次を行う:
error を ThrowCompletion (新たに生成された
SyntaxError オブジェクト) とする。
ContinueModuleLoading (state ,
error ) を実行する。
それ以外で、module .[[LoadedModules]] に LoadedModuleRequest
レコード record が含まれ、かつ
ModuleRequestsEqual (record ,
request ) が true
である場合、次を行う:
InnerModuleLoading (state ,
record .[[Module]] ) を実行する。
それ以外の場合、次を行う:
HostLoadImportedModule (module ,
request , state .[[HostDefined]] ,
state ) を実行する。
注:HostLoadImportedModule
は FinishLoadingImportedModule
を呼び出し、ContinueModuleLoading
を通じてグラフロード処理に再入します。
もし state .[[IsLoading]] が
false
なら、unused を返す。
アサート : state .[[PendingModulesCount]] ≥ 1 である。
state .[[PendingModulesCount]] を
state .[[PendingModulesCount]] - 1
に設定する。
もし state .[[PendingModulesCount]] = 0
なら、次を行う:
state .[[IsLoading]] を
false に設定する。
各 循環モジュールレコード
loaded について、state .[[Visited]] の中で次を行う:
もし loaded .[[Status]]
が new なら、loaded .[[Status]] を
unlinked に設定する。
! Call (state .[[PromiseCapability]] .[[Resolve]] ,
undefined , « undefined »)
を実行する。
unused を返す。
16.2.1.6.1.1.2 ContinueModuleLoading
(state , moduleCompletion )
抽象操作 ContinueModuleLoading は、state (GraphLoadingState
レコード )および moduleCompletion (normal completion
containing の モジュールレコード または
throw
completion )を引数に取り、unused
を返します。この操作は HostLoadImportedModule
の呼び出し後にロード処理へ再入するために使用されます。呼び出されると以下の手順を実行します:
もし state .[[IsLoading]] が
false なら、unused を返す。
もし moduleCompletion が normal
completion なら、次を行う:
InnerModuleLoading (state ,
moduleCompletion .[[Value]] )
を実行する。
それ以外の場合、次を行う:
state .[[IsLoading]] を
false に設定する。
! Call (state .[[PromiseCapability]] .[[Reject]] ,
undefined , « moduleCompletion .[[Value]] ») を実行する。
unused を返す。
16.2.1.6.1.2 Link ( )
循環モジュールレコード module の
Link 具体メソッドは、引数を取らず、normal
completion containing unused または
throw
completion を返します。成功時は、このモジュールの [[Status]] が unlinked から
linked に遷移します。失敗時は例外が投げられ、このモジュールの [[Status]] は unlinked
のままです。(実際の処理の多くは補助関数 InnerModuleLinking
によって行われます。)呼び出されると以下の手順を実行します:
アサート : module .[[Status]] は unlinked ,
linked , evaluating-async ,
evaluated のいずれかである。
stack を新たな空の リスト
とする。
result を Completion (InnerModuleLinking (module ,
stack , 0)) とする。
もし result が abrupt
completion なら、次を行う:
各 循環モジュールレコード
m について、stack の中で次を行う:
アサート :
m .[[Status]] は
linking である。
m .[[Status]] を
unlinked に設定する。
アサート : module .[[Status]] は unlinked
である。
? result を返す。
アサート : module .[[Status]] は linked ,
evaluating-async , evaluated
のいずれかである。
アサート : stack は空である。
unused を返す。
16.2.1.6.1.2.1 InnerModuleLinking
(module , stack , index )
抽象操作 InnerModuleLinking は、module (モジュールレコード )、stack (循環モジュールレコード
のリスト)、index (0以上の整数 )を引数に取り、normal completion
containing 0以上の 整数 または throw
completion を返します。Link から呼び出され、module
の実際のリンク処理および依存グラフ内の他のすべてのモジュールに対して再帰的に呼ばれます。stack と
index 、およびモジュールの [[DFSAncestorIndex]]
フィールドは、深さ優先探索(DFS)を追跡するために使われます。特に、[[DFSAncestorIndex]]
は強連結成分(SCC)を発見するために使われ、SCC 内のすべてのモジュールが同時に linked
へ遷移します。呼び出されると以下の手順を実行します:
もし module が 循環モジュールレコード
でなければ、次を行う:
? module .Link() を実行する。
index を返す。
もし module .[[Status]] が
linking , linked ,
evaluating-async ,
evaluated のいずれかであれば、index を返す。
アサート : module .[[Status]] は unlinked
である。
module .[[Status]] を
linking に設定する。
moduleIndex を index とする。
module .[[DFSAncestorIndex]] を
index に設定する。
index を index + 1 に設定する。
module を stack に追加する。
各 ModuleRequest Record
request について、module .[[RequestedModules]] の中で次を行う:
requiredModule を GetImportedModule (module ,
request ) とする。
index を ? InnerModuleLinking (requiredModule ,
stack , index ) に設定する。
もし requiredModule が 循環モジュールレコード
であれば、次を行う:
アサート :
requiredModule .[[Status]] は
linking ,
linked ,
evaluating-async ,
evaluated のいずれかである。
アサート :
requiredModule .[[Status]] が
linking である場合に限り、stack
は requiredModule を含む。
もし requiredModule .[[Status]] が
linking であれば、次を行う:
module .[[DFSAncestorIndex]] を
min (module .[[DFSAncestorIndex]] ,
requiredModule .[[DFSAncestorIndex]] )
に設定する。
? module .InitializeEnvironment() を実行する。
アサート : module は
stack の中にちょうど1回現れる。
アサート : module .[[DFSAncestorIndex]] ≤ moduleIndex
である。
もし module .[[DFSAncestorIndex]] =
moduleIndex なら、次を行う:
done を false とする。
done が false の間、繰り返す:
requiredModule を stack の最後の要素とする。
stack の最後の要素を削除する。
アサート :
requiredModule は 循環モジュールレコード
である。
requiredModule .[[Status]] を
linked に設定する。
もし requiredModule および module が同じ
モジュールレコード
であれば、done を true に設定する。
index を返す。
16.2.1.6.1.3 Evaluate ( )
循環モジュールレコード module の
Evaluate 具体メソッドは引数を取らず、Promise を返す。Evaluate はこのモジュールの [[Status]] を linked から
evaluating-async または evaluated
へ遷移させる。ある強連結成分内で初めて呼び出された場合、Evaluate は、モジュールの評価が完了した時に解決される Promise を生成し返す。この
Promise は、その成分の [[CycleRoot]] の [[TopLevelCapability]] フィールドに保存される。以降、成分内の任意のモジュールで Evaluate
を呼び出すと、同じ Promise が返される。(ほとんどの処理は補助関数 InnerModuleEvaluation
によって行われる。)呼び出されたとき、次の手順を実行する:
Assert : この Evaluate 呼び出しは、surrounding agent 内で他の
Evaluate の呼び出しと同時に実行されていない。
Assert : module .[[Status]] は
linked 、evaluating-async 、または
evaluated のいずれかである。
もし module .[[Status]] が
evaluating-async または evaluated
であれば、module を module .[[CycleRoot]] に設定する。
もし module .[[TopLevelCapability]] が
empty でない場合、
module .[[TopLevelCapability]] .[[Promise]] を返す。
stack を新しい空の List
とする。
capability を ! NewPromiseCapability (%Promise% ) とする。
module .[[TopLevelCapability]] に
capability を設定する。
result を Completion (InnerModuleEvaluation (module ,
stack , 0)) とする。
もし result が abrupt
completion であれば、
stack の各 循環モジュールレコード
m について、次を実行する:
Assert :
m .[[Status]] は
evaluating である。
Assert :
m .[[AsyncEvaluationOrder]] は
unset である。
m .[[Status]] を
evaluated に設定する。
m .[[EvaluationError]] を
result に設定する。
Assert : module .[[Status]] は
evaluated である。
Assert : module .[[EvaluationError]] と result は同じ
Completion
Record である。
! Call (capability .[[Reject]] , undefined , «
result .[[Value]] ») を実行する。
それ以外の場合、
Assert : module .[[Status]] は
evaluating-async または
evaluated のいずれかである。
Assert : module .[[EvaluationError]] は
empty である。
もし module .[[Status]] が
evaluated であれば、
注: これは module の評価が同期的に完了したことを意味する。
Assert :
module .[[AsyncEvaluationOrder]] は
unset である。
! Call (capability .[[Resolve]] ,
undefined , « undefined
») を実行する。
Assert : stack
は空である。
capability .[[Promise]] を返す。
16.2.1.6.1.3.1 InnerModuleEvaluation (
module , stack , index )
抽象操作 InnerModuleEvaluation は、module (
Module Record )、
stack (List で、
Cyclic Module Records のリスト)、
index (非負の integer )を引数に取り、
非負の integer を含む
normal
completion か、
throw
completion のいずれかを返す。
この操作は Evaluate により、module
の実際の評価処理や、依存関係グラフ上の他のすべてのモジュールに対して再帰的に使用される。
stack および index のパラメータ、また module の [[DFSAncestorIndex]] フィールドは、
InnerModuleLinking
でと同様に使われる。
呼び出されたとき、次の手順を実行する:
もし module が Cyclic Module
Record でない場合、
? EvaluateModuleSync (module )
を実行する。
index を返す。
もし module .[[Status]] が
evaluating-async または
evaluated のいずれかの場合、
もし module .[[EvaluationError]] が
empty なら、index を返す。
それ以外なら、? module .[[EvaluationError]] を返す。
もし module .[[Status]] が
evaluating なら、index を返す。
Assert : module .[[Status]] は linked である。
module .[[Status]] を
evaluating に設定する。
moduleIndex を index とする。
module .[[DFSAncestorIndex]] を
index に設定する。
module .[[PendingAsyncDependencies]]
を 0 に設定する。
index を index + 1 に設定する。
module を stack に追加する。
module .[[RequestedModules]] の各
ModuleRequest Record
request について、以下を行う:
requiredModule を GetImportedModule (module ,
request ) とする。
index を ? InnerModuleEvaluation (requiredModule ,
stack , index ) に設定する。
もし requiredModule が Cyclic Module
Record なら、
Assert :
requiredModule .[[Status]] は
evaluating 、evaluating-async 、evaluated
のいずれかである。
Assert :
requiredModule .[[Status]] が
evaluating であるのは stack
に requiredModule が含まれる場合に限る。
もし requiredModule .[[Status]] が
evaluating なら、
module .[[DFSAncestorIndex]] を
min (module .[[DFSAncestorIndex]] ,
requiredModule .[[DFSAncestorIndex]] )
に設定する。
それ以外なら、
requiredModule を
requiredModule .[[CycleRoot]] に設定する。
Assert :
requiredModule .[[Status]] は
evaluating-async または
evaluated のいずれかである。
もし requiredModule .[[EvaluationError]] が
empty でなければ、?
requiredModule .[[EvaluationError]] を返す。
もし requiredModule .[[AsyncEvaluationOrder]] が
integer なら、
module .[[PendingAsyncDependencies]]
を module .[[PendingAsyncDependencies]]
+ 1 にする。
module を
requiredModule .[[AsyncParentModules]]
に追加する。
もし module .[[PendingAsyncDependencies]] > 0 または
module .[[HasTLA]] が
true なら、
Assert :
module .[[AsyncEvaluationOrder]] は
unset である。
module .[[AsyncEvaluationOrder]] を IncrementModuleAsyncEvaluationCount ()
に設定する。
もし module .[[PendingAsyncDependencies]] = 0
なら、ExecuteAsyncModule (module )
を実行する。
それ以外なら、
? module .ExecuteModule()
を実行する。
Assert : module は
stack にちょうど1回だけ現れる。
Assert : module .[[DFSAncestorIndex]] ≤ moduleIndex
である。
もし module .[[DFSAncestorIndex]] =
moduleIndex なら、
done を false とする。
done が false の間、繰り返す:
requiredModule を stack の最後の要素とする。
stack の最後の要素を削除する。
Assert :
requiredModule は Cyclic Module
Record である。
Assert :
requiredModule .[[AsyncEvaluationOrder]] は
integer または
unset のいずれかである。
もし requiredModule .[[AsyncEvaluationOrder]] が
unset
なら、requiredModule .[[Status]] を
evaluated に設定する。
それ以外なら、requiredModule .[[Status]] を
evaluating-async に設定する。
もし requiredModule と module が同じ
Module
Record なら、done を
true に設定する。
requiredModule .[[CycleRoot]] を
module に設定する。
index を返す。
注 1
InnerModuleEvaluation によって走査されている間、モジュールは
evaluating 状態である。実行が完了した場合
evaluated 状態となり、または実行中に [[HasTLA]] フィールドが true
または非同期依存関係を持つ場合は evaluating-async 状態となる。
注 2
非同期サイクルのモジュールに依存する他のモジュールは、そのサイクルが evaluating
状態でない場合、[[CycleRoot]]
を通じてサイクルのルートの実行に依存することになる。これにより、サイクルの状態はルートモジュールの状態を通じて単一の強連結成分として扱うことができる。
16.2.1.6.1.3.2 ExecuteAsyncModule (
module )
抽象操作 ExecuteAsyncModule は、引数 module (
循環モジュールレコード )
を受け取り、unused を返す。呼び出されたとき、次の手順を実行する:
Assert : module .[[Status]] は evaluating
または evaluating-async のいずれかである。
Assert : module .[[HasTLA]] は true である。
capability を ! NewPromiseCapability (%Promise% ) とする。
fulfilledClosure を、パラメータなしで module
をキャプチャし、呼び出された時に以下を実行する新しい Abstract
Closure とする:
AsyncModuleExecutionFulfilled (module )
を実行する。
NormalCompletion (undefined )
を返す。
onFulfilled を CreateBuiltinFunction (fulfilledClosure ,
0, "" , « ») とする。
rejectedClosure を、パラメータ (error ) で
module をキャプチャし、呼び出された時に以下を実行する新しい Abstract Closure
とする:
AsyncModuleExecutionRejected (module ,
error ) を実行する。
NormalCompletion (undefined )
を返す。
onRejected を CreateBuiltinFunction (rejectedClosure ,
0, "" , « ») とする。
PerformPromiseThen (capability .[[Promise]] , onFulfilled ,
onRejected ) を実行する。
! module .ExecuteModule (capability )
を実行する。
unused を返す。
16.2.1.6.1.3.3 GatherAvailableAncestors (
module , execList )
抽象操作 GatherAvailableAncestors は、引数 module (
循環モジュールレコード )と、
execList (List で
循環モジュールレコード のリスト)を受け取り、
unused を返す。呼び出されたとき、次の手順を実行する:
module .[[AsyncParentModules]] の各
循環モジュールレコード
m について、以下を行う:
もし execList に m が含まれておらず、かつ
m .[[CycleRoot]] .[[EvaluationError]] が
empty であれば、以下を行う:
Assert :
m .[[Status]] は
evaluating-async である。
Assert :
m .[[EvaluationError]] は
empty である。
Assert :
m .[[AsyncEvaluationOrder]] は
integer である。
Assert :
m .[[PendingAsyncDependencies]]
> 0 である。
m .[[PendingAsyncDependencies]] を
m .[[PendingAsyncDependencies]] - 1
に設定する。
もし m .[[PendingAsyncDependencies]] = 0
なら、以下を行う:
m を execList に追加する。
もし m .[[HasTLA]] が
false であれば、GatherAvailableAncestors (m ,
execList ) を実行する。
unused を返す。
注
ルート module
の非同期実行が完了したとき、この関数は同期的に一緒に実行可能なモジュールのリストを決定し、execList に追加する。
16.2.1.6.1.3.4 AsyncModuleExecutionFulfilled (
module )
抽象操作 AsyncModuleExecutionFulfilled は、引数 module (
循環モジュールレコード )を受け取り、
unused を返す。呼び出されたとき、以下の手順を実行する:
もし module .[[Status]] が
evaluated なら、
Assert :
module .[[EvaluationError]] は
empty ではない。
unused を返す。
Assert : module .[[Status]] は
evaluating-async である。
Assert : module .[[AsyncEvaluationOrder]] は integer である。
Assert : module .[[EvaluationError]] は
empty である。
module .[[AsyncEvaluationOrder]] を
done に設定する。
module .[[Status]] を
evaluated に設定する。
もし module .[[TopLevelCapability]] が
empty でなければ、
Assert :
module .[[CycleRoot]] と
module は同じ Module
Record である。
! Call (module .[[TopLevelCapability]] .[[Resolve]] ,
undefined , « undefined »)
を実行する。
execList を新しい空の List
とする。
GatherAvailableAncestors (module ,
execList ) を実行する。
Assert : execList
の全要素は、その [[AsyncEvaluationOrder]] フィールドが
integer に設定され、[[PendingAsyncDependencies]] フィールドが 0 に設定され、[[EvaluationError]] フィールドが
empty である。
sortedExecList を、execList の要素を [[AsyncEvaluationOrder]] フィールドで昇順にソートした
List
とする。
sortedExecList の各 循環モジュールレコード
m について、以下を行う:
もし m .[[Status]] が
evaluated なら、
Assert :
m .[[EvaluationError]] は
empty ではない。
それ以外で m .[[HasTLA]] が
true なら、
ExecuteAsyncModule (m )
を実行する。
それ以外の場合、
result を m .ExecuteModule()
とする。
もし result が abrupt
completion であれば、
AsyncModuleExecutionRejected (m ,
result .[[Value]] ) を実行する。
それ以外の場合、
m .[[AsyncEvaluationOrder]]
を done に設定する。
m .[[Status]]
を evaluated に設定する。
もし m .[[TopLevelCapability]] が
empty でなければ、
Assert :
m .[[CycleRoot]] と
m は同じ Module
Record である。
! Call (m .[[TopLevelCapability]] .[[Resolve]] ,
undefined , «
undefined ») を実行する。
unused を返す。
16.2.1.6.1.3.5 AsyncModuleExecutionRejected (
module , error )
抽象操作 AsyncModuleExecutionRejected は、module (
循環モジュールレコード )と
error (ECMAScript
言語値 )を引数に取り、
unused を返す。呼び出されたとき、次の手順を実行する:
もし module .[[Status]] が
evaluated なら、
Assert :
module .[[EvaluationError]] は
empty ではない。
unused を返す。
Assert : module .[[Status]] は
evaluating-async である。
Assert : module .[[AsyncEvaluationOrder]] は integer である。
Assert : module .[[EvaluationError]] は
empty である。
module .[[EvaluationError]] を
ThrowCompletion (error )
に設定する。
module .[[Status]] を
evaluated に設定する。
module .[[AsyncEvaluationOrder]] を
done に設定する。
注: module .[[AsyncEvaluationOrder]] は
AsyncModuleExecutionFulfilled
との対称性のため done に設定される。
InnerModuleEvaluation
では、モジュールの [[EvaluationError]] が
empty でない場合、[[AsyncEvaluationOrder]] の値は使用されない。
module .[[AsyncParentModules]] の各
循環モジュールレコード
m について、以下を実行する:
AsyncModuleExecutionRejected (m ,
error ) を実行する。
もし module .[[TopLevelCapability]] が
empty でなければ、
Assert :
module .[[CycleRoot]] と
module は同じ Module
Record である。
! Call (module .[[TopLevelCapability]] .[[Reject]] ,
undefined , « error ») を実行する。
unused を返す。
16.2.1.6.2 循環モジュールレコードグラフの例
この非規範的なセクションでは、いくつかの一般的なモジュールグラフのリンクおよび評価の一連の例を示し、特にエラーがどのように発生するかに焦点を当てます。
まず、次のシンプルなモジュールグラフを考えます。
図2:単純なモジュールグラフ
まず、エラー条件がないと仮定します。ホスト が最初に A .LoadRequestedModules()
を呼び出すと、仮定上正常に完了し、B および C の依存関係(それぞれ C
となし)を再帰的にロードし、A .[[Status]] = B .[[Status]] = C .[[Status]] =
unlinked に設定されます。その後、ホスト が A .Link()
を呼び出すと、再び仮定上正常に完了し、A .[[Status]] = B .[[Status]] = C .[[Status]] =
linked となります。これらの準備ステップはいつでも実行可能です。後で、ホスト がモジュールの副作用が発生する準備ができた時、A .Evaluate()
を呼び出すことができ、正常に完了し、Promise が undefined
で解決されます(再び仮定上)。この際、C 、次に B が再帰的に評価されます。この時点で各モジュールの [[Status]] は evaluated となります。
次に、リンクエラーを含むケースを考えます。A .LoadRequestedModules() の正常な呼び出し後、InnerModuleLinking が C
で成功し、その後 B で失敗する場合(例えば B が C が提供しないものをインポートしようとした場合)、元の
A .Link() は失敗し、A および B の [[Status]] は unlinked
のままとなります。C の [[Status]] は
linked になっています。
最後に、Link() の正常な呼び出し後の評価エラーのケースを考えます。InnerModuleEvaluation が
C で成功し、その後 B で失敗する場合(例えば B に例外を投げるコードがある場合)、元の
A .Evaluate() は失敗し、拒否された Promise を返します。結果として生じる例外は A および
B の [[EvaluationError]] フィールドに記録され、それらの [[Status]] は evaluated となります。C
も evaluated となりますが、A および B と異なり [[EvaluationError]] はありません(正常に評価されたため)。例外を格納することで、ホスト が A または
B の Evaluate() メソッドを再利用しようとした際、同じ例外に遭遇することを保証します。(ホスト は 循環モジュールレコード
の再利用を要求されません。同様に、ホスト はこれらのメソッドによって投げられる例外オブジェクトの公開を要求されません。しかし、仕様はそのような利用を可能としています。)
次に、異なる種類のエラー条件を考えます:
図3:解決不可能なモジュールを含むモジュールグラフ
このシナリオでは、モジュール A が他のモジュールへの依存関係を宣言していますが、そのモジュールの Module Record
が存在しません。つまり、HostLoadImportedModule が
FinishLoadingImportedModule
を例外付きで呼び出します。これは、該当するリソースが存在しない場合や、リソースは存在するが ParseModule
がソーステキストの解析時にエラーを返す場合など、さまざまな理由で発生し得ます。ホスト は FinishLoadingImportedModule
に渡す completion を通じて失敗原因を公開することもできます。いずれの場合も、この例外は読み込み失敗を引き起こし、A の [[Status]] は new のままとなります。
ここでの読み込み、リンク、評価エラーの違いは、次の特徴によるものです:
Evaluation
は一度だけ実行されなければならず、副作用が発生する可能性があるため、評価が既に行われたかどうか(失敗も含めて)を記憶しておくことが重要です。(エラーの場合も例外を記憶するのが理にかなっており、そうでないと
Evaluate() の後続呼び出しごとに新しい例外を生成しなければならなくなります。)
一方、リンクは副作用がなく、失敗しても後で何度でも再試行可能です。
読み込みは ホスト と密接に連携しており、例えば一時的なネットワーク障害などで失敗した場合、いくつかのホストでは失敗した読み込みの再試行をユーザーに許可することが望ましい場合があります。
次に、循環を含むモジュールグラフを考えます:
図4:循環モジュールグラフ
ここでは、エントリーポイントがモジュール A であると仮定します。ホスト が A .LoadRequestedModules()
を呼び出し、InnerModuleLoading が A
に対して実行されます。これにより B および C に対して InnerModuleLoading
が呼び出されます。循環により再び A に対して InnerModuleLoading
が呼び出されますが、この時点では A
の依存関係の読み込みは既に開始されているため何もしません。このグラフ内のすべてのモジュールが正常に読み込まれると、その [[Status]] は同時に new から
unlinked に遷移します。
その後、ホスト が
A .Link() を呼び出し、InnerModuleLinking が A
に対して実行されます。これにより B に対しても InnerModuleLinking
が呼び出され、循環により再び A で InnerModuleLinking が呼び出されますが、この時点で
A .[[Status]] はすでに linking
なので何もしません。B .[[Status]] は制御が A に戻った時点でも
linking のままですが、InnerModuleLinking が
C に対して呼び出されます。これが返ると C .[[Status]] は
linked となり、A および B も同時に
linking から linked
へ遷移します。これは、それらが強連結成分を形成しているため設計上そうなっています。モジュールグラフが深さ優先探索で走査されるため、同じSCC内のモジュールの状態を同時に遷移させることが可能です。
循環モジュールグラフの評価フェーズでも、成功ケースでは同様の処理が行われます。
次に、A にリンクエラーがあるケースを考えます。例えば、C
から存在しない束縛をインポートしようとした場合です。この場合、上記の処理は依然として行われますが、A への2度目の InnerModuleLinking
呼び出しから早期リターンが起こります。ただし、元の InnerModuleLinking
への巻き戻し時に、InitializeEnvironment 中、特に C .ResolveExport() の直後に失敗します。投げられた
SyntaxError 例外は A .Link まで伝播し、現在スタック上にあるすべてのモジュール(常にまだ
linking のモジュール)をリセットします。したがって、A および B は
unlinked となります。C は linked
のままです。
または、A
に評価エラーがあるケースを考えます。例えば、そのソースコードが例外を投げる場合です。この場合、上記の評価時のアナロジーの処理が行われますが、A
への2度目の InnerModuleEvaluation
呼び出しから早期リターンが起こります。ただし、元の InnerModuleEvaluation
への巻き戻し時に、仮定上失敗します。投げられた例外は A .Evaluate() まで伝播し、現在スタック上にあるすべてのモジュール(まだ
evaluating のモジュール)および [[AsyncParentModules]] (これはトップレベル await
を含む、またはそれに依存するモジュールのチェーンを形成し、依存グラフ全体で AsyncModuleExecutionRejected
アルゴリズムを通じて伝播されます)にエラーが記録されます。したがって、A および B は
evaluated となり、例外は両方の [[EvaluationError]]
フィールドに記録されます。一方、C は evaluated で [[EvaluationError]] はありません。
最後に、すべてのモジュールが非同期的に完了するサイクルを含むモジュールグラフを考えます:
図5:非同期循環モジュールグラフ
読み込みとリンクはこれまで通り行われ、すべてのモジュールの [[Status]] は
linked に設定されます。
A .Evaluate() を呼び出すと、InnerModuleEvaluation が
A 、B 、D に対して呼び出され、全て evaluating
に遷移します。次に InnerModuleEvaluation が再び
A に呼び出されますが、すでに evaluating なので何もしません。この時点で
D .[[PendingAsyncDependencies]] は 0 なので、ExecuteAsyncModule (D )
が呼び出され、D .ExecuteModule が新しい PromiseCapability で非同期実行を追跡しつつ呼び出されます。InnerModuleEvaluation の
B への巻き戻し時に B .[[PendingAsyncDependencies]]
が 1 となり、B .[[AsyncEvaluationOrder]] が 1 となります。元の
InnerModuleEvaluation の
A への巻き戻し時に A .[[PendingAsyncDependencies]]
が 1 となります。次の A の依存関係ループでは、InnerModuleEvaluation が
C 、さらに D (再び何もしない)と E に呼び出されます。E
は依存関係を持たず循環にも属していないので、ExecuteAsyncModule (E )
が D と同様に呼び出され、直ちにスタックから除去されます。再度 InnerModuleEvaluation の
C への巻き戻し時に C .[[AsyncEvaluationOrder]] が 3
となり、A の依存関係ループが終了し A .[[AsyncEvaluationOrder]] が 4 となり、強連結成分全体がスタックから除去され、全てのモジュールが同時に
evaluating-async に遷移します。この時点で各モジュールのフィールドは 表48 の通りです。
表48:初めて Evaluate() を呼び出した後のモジュールフィールド
フィールド
モジュール
A
B
C
D
E
[[DFSAncestorIndex]]
0
0
0
0
4
[[Status]]
evaluating-async
evaluating-async
evaluating-async
evaluating-async
evaluating-async
[[AsyncEvaluationOrder]]
4
1
3
0
2
[[AsyncParentModules]]
« »
« A »
« A »
« B , C »
« C »
[[PendingAsyncDependencies]]
2 (B と C )
1 (D )
2 (D と E )
0
0
ここで、E が最初に実行完了すると仮定します。その場合、AsyncModuleExecutionFulfilled
が呼び出され、E .[[Status]] が
evaluated となり、C .[[PendingAsyncDependencies]] が 1 へ減算されます。更新後の各モジュールのフィールドは
表49 の通りです。
表49:モジュール E 実行後のモジュールフィールド
フィールド
モジュール
C
E
[[DFSAncestorIndex]]
0
4
[[Status]]
evaluating-async
evaluated
[[AsyncEvaluationOrder]]
3
done
[[AsyncParentModules]]
« A »
« C »
[[PendingAsyncDependencies]]
1 (D )
0
次に D が実行完了します(実行中だった唯一のモジュール)。このとき AsyncModuleExecutionFulfilled
が再度呼び出され、D .[[Status]] が
evaluated となります。実行可能な祖先は B ([[AsyncEvaluationOrder]] は 1)および C ([[AsyncEvaluationOrder]] は 3)であり、B
が先に処理されます:B .[[PendingAsyncDependencies]] が 0
へ減算され、ExecuteAsyncModule が
B に対して呼び出され、実行が開始されます。C .[[PendingAsyncDependencies]] も 0 へ減算され、C
の実行も開始されます(B に await が含まれる場合は並行で実行される可能性あり)。更新後の各モジュールのフィールドは
表50 の通りです。
表50:モジュール D 実行後のモジュールフィールド
フィールド
モジュール
B
C
D
[[DFSAncestorIndex]]
0
0
0
[[Status]]
evaluating-async
evaluating-async
evaluated
[[AsyncEvaluationOrder]]
1
3
done
[[AsyncParentModules]]
« A »
« A »
« B , C »
[[PendingAsyncDependencies]]
0
0
0
次に C が実行完了したと仮定します。その場合、AsyncModuleExecutionFulfilled
が再度呼び出され、C .[[Status]] が
evaluated となり、A .[[PendingAsyncDependencies]] が 1 へ減算されます。更新後のフィールドは 表51 の通りです。
表51:モジュール C 実行後のモジュールフィールド
フィールド
モジュール
A
C
[[DFSAncestorIndex]]
0
0
[[Status]]
evaluating-async
evaluated
[[AsyncEvaluationOrder]]
4
done
[[AsyncParentModules]]
« »
« A »
[[PendingAsyncDependencies]]
1 (B )
0
その後、B が実行完了します。その場合、AsyncModuleExecutionFulfilled
が再度呼び出され、B .[[Status]] が
evaluated となります。A .[[PendingAsyncDependencies]] が 0 へ減算され、ExecuteAsyncModule
が呼び出され、実行が開始されます。更新後のフィールドは 表52
の通りです。
表52:モジュール B 実行後のモジュールフィールド
フィールド
モジュール
A
B
[[DFSAncestorIndex]]
0
0
[[Status]]
evaluating-async
evaluated
[[AsyncEvaluationOrder]]
4
done
[[AsyncParentModules]]
« »
« A »
[[PendingAsyncDependencies]]
0
0
最後に A が実行完了します。その場合、AsyncModuleExecutionFulfilled
が再度呼び出され、A .[[Status]] が
evaluated となります。この時点で A .[[TopLevelCapability]] の Promise(A .Evaluate()
から返されたもの)が解決され、これでこのモジュールグラフの処理は終了します。更新後のフィールドは 表53 の通りです。
表53:モジュール A 実行後のモジュールフィールド
フィールド
モジュール
A
[[DFSAncestorIndex]]
0
[[Status]]
evaluated
[[AsyncEvaluationOrder]]
done
[[AsyncParentModules]]
« »
[[PendingAsyncDependencies]]
0
または、C が実行失敗し、B の実行完了前にエラーを返すケースを考えます。その場合、AsyncModuleExecutionRejected
が呼び出され、C .[[Status]] が
evaluated となり、C .[[EvaluationError]] にエラーが設定されます。そしてこのエラーはすべての AsyncParentModules
に伝播され、各々に AsyncModuleExecutionRejected
が実行されます。更新後のフィールドは 表54
の通りです。
表54:モジュール C がエラーで終了した後のモジュールフィールド
フィールド
モジュール
A
C
[[DFSAncestorIndex]]
0
0
[[Status]]
evaluated
evaluated
[[AsyncEvaluationOrder]]
done
done
[[AsyncParentModules]]
« »
« A »
[[PendingAsyncDependencies]]
1 (B )
0
[[EvaluationError]]
empty
C の評価エラー
A は C と同じエラーで拒否されます。なぜなら C が AsyncModuleExecutionRejected
を A に C のエラーとともに呼び出すからです。A .[[Status]] は evaluated となります。この時点で
A .[[TopLevelCapability]] の
Promise(A .Evaluate() から返されたもの)は拒否されます。更新後のフィールドは 表55 の通りです。
表55:モジュール A が拒否された後のモジュールフィールド
フィールド
モジュール
A
[[DFSAncestorIndex]]
0
[[Status]]
evaluated
[[AsyncEvaluationOrder]]
done
[[AsyncParentModules]]
« »
[[PendingAsyncDependencies]]
0
[[EvaluationError]]
C の Evaluation エラー
その後、B がエラーなしで実行完了します。その場合、AsyncModuleExecutionFulfilled
が再度呼び出され、B .[[Status]] が
evaluated となります。GatherAvailableAncestors が
B に対して呼び出されます。ただし、A .[[CycleRoot]] は
A で評価エラーを持つため、返される sortedExecList に追加されず、AsyncModuleExecutionFulfilled
はそのまま終了します。B の将来のインポーターは、サイクルルート A に設定された C 由来の評価エラーによる
B .[[CycleRoot]] .[[EvaluationError]] の拒否を解決することになります。更新後のフィールドは 表56 の通りです。
表 56: モジュール B がエラーとなるグラフで実行を完了した後のモジュールフィールド
フィールド
モジュール
A
B
[[DFSAncestorIndex]]
0
0
[[Status]]
evaluated
evaluated
[[AsyncEvaluationOrder]]
4
1
[[AsyncParentModules]]
« »
« A »
[[PendingAsyncDependencies]]
0
0
[[EvaluationError]]
C の Evaluation エラー
empty
16.2.1.7 ソーステキストモジュールレコード
ソーステキストモジュールレコード は、
ECMAScriptソーステキスト
(11 )
から定義されたモジュールについての情報を表現するために使用されるものである。
これは目標記号
Module を用いて構文解析される。
そのフィールドには、このモジュールによってインポートおよびエクスポートされる名前に関する要約情報が含まれており、
その具体メソッドはこれらの要約を使ってモジュールのリンクと評価を行う。
ソーステキストモジュールレコード は、
抽象モジュールレコード 型の
他のサブクラスと共にモジュールグラフ内で存在することができ、
循環モジュールレコード
型の他のサブクラスとサイクルに参加することもできる。
表45 で定義されているフィールドに加え、
ソーステキストモジュールレコード は
表57 に記載されている追加フィールドを持つ。
これらの各フィールドはParseModule で初期設定される。
表57: ソーステキストモジュールレコード の追加フィールド
フィールド名
値の型
意味
[[ECMAScriptCode]]
構文ノード
このモジュールのソーステキストをModule を目標記号として構文解析した結果。
目標記号
を使用。
[[Context]]
ECMAScriptコード実行コンテキスト またはempty
このモジュールに関連付けられた実行コンテキスト 。
モジュールの環境が初期化されるまではempty となる。
[[ImportMeta]]
オブジェクトまたはempty
import.metaメタプロパティを介して公開されるオブジェクト。ECMAScriptコードでアクセスされるまでempty となる。
[[ImportEntries]]
リスト
(ImportEntryレコード のリスト)
このモジュールのコードから導出されたImportEntryレコードのリスト 。
[[LocalExportEntries]]
リスト
(ExportEntryレコード のリスト)
このモジュールのコードから導出された、そのモジュール内で宣言されたものに対応するExportEntryレコードのリスト 。
[[IndirectExportEntries]]
リスト
(ExportEntryレコード のリスト)
このモジュールのコードから導出された、モジュール内で発生する再エクスポートされたインポートやexport * as namespace宣言によるエクスポートに対応するExportEntryレコードのリスト 。
[[StarExportEntries]]
リスト
(ExportEntryレコード のリスト)
このモジュールのコードから導出された、モジュール内で発生するexport *宣言(ただしexport * as namespace宣言を除く)に対応するExportEntryレコードのリスト 。
ImportEntryレコード は、
1つの宣言的インポートについての情報を要約したレコード である。
各ImportEntryレコード は
表58 で定義されているフィールドを持つ:
表58: ImportEntryレコード のフィールド
フィールド名
値の型
意味
[[ModuleRequest]]
ModuleRequestレコード
ModuleRequestレコード であり、
ModuleSpecifier および
ImportDeclaration のインポート属性を表す。
[[ImportName]]
文字列またはnamespace-object
[[ModuleRequest]] で識別されるモジュールによってエクスポートされる所望のバインディングの名前。
namespace-object は、ターゲットモジュールの名前空間オブジェクトへのインポートを意味する。
[[LocalName]]
文字列
インポート元モジュール内からインポートされた値にローカルにアクセスするために使用される名前。
注1
表59 は、
構文的なインポート形式を表すために使用されるImportEntryレコードのフィールド例を示す:
表59(参考): インポート形式のImportEntryレコード へのマッピング
インポート文の形式
[[ModuleRequest]]
[[ImportName]]
[[LocalName]]
import v from "mod";
"mod"
"default"
"v"
import * as ns from "mod";
"mod"
namespace-object
"ns"
import {x} from "mod";
"mod"
"x"
"x"
import {x as v} from "mod";
"mod"
"x"
"v"
import "mod";
ImportEntryレコード は作成されない。
ExportEntryレコード は、
1つの宣言的エクスポートについての情報を要約したレコード である。
各ExportEntryレコード は
表60 で定義されているフィールドを持つ:
表60: ExportEntryレコード のフィールド
注2
表61 は、
構文的なエクスポート形式を表すために使用されるExportEntryレコードのフィールド例を示す:
表61(参考): エクスポート形式のExportEntryレコード へのマッピング
エクスポート文の形式
[[ExportName]]
[[ModuleRequest]]
[[ImportName]]
[[LocalName]]
export var v;
"v"
null
null
"v"
export default function f() {}
"default"
null
null
"f"
export default function () {}
"default"
null
null
"*default*"
export default 42;
"default"
null
null
"*default*"
export {x};
"x"
null
null
"x"
export {v as x};
"x"
null
null
"v"
export {x} from "mod";
"x"
"mod"
"x"
null
export {v as x} from "mod";
"x"
"mod"
"v"
null
export * from "mod";
null
"mod"
all-but-default
null
export * as ns from "mod";
"ns"
"mod"
all
null
以下の定義は、ソーステキストモジュールレコード に必要な具体メソッドおよびその他の
抽象操作 を指定する。
16.2.1.7.1 ParseModule ( sourceText ,
realm , hostDefined )
抽象操作 ParseModule は、引数 sourceText (ECMAScript
ソーステキスト )、realm (Realm
レコード )、hostDefined (任意の値)を受け取り、ソーステキストモジュールレコード または空でないリスト (SyntaxError オブジェクトのリスト)を返す。この操作は、sourceText をModule として構文解析した結果に基づいてソーステキストモジュールレコード を作成する。呼び出し時に以下の手順を実行する:
body を ParseText (sourceText ,
Module ) とする。
もし body がエラーの リスト であれば、body
を返す。
requestedModules を ModuleRequests
of body とする。
importEntries を ImportEntries
of body とする。
importedBoundNames を ImportedLocalNames (importEntries )
とする。
indirectExportEntries を新しい空の リスト とする。
localExportEntries を新しい空の リスト とする。
starExportEntries を新しい空の リスト とする。
exportEntries を ExportEntries
of body とする。
exportEntries の各 ExportEntry
Record ee について、以下を行う:
もし ee .[[ModuleRequest]] が
null なら、
もし importedBoundNames に ee .[[LocalName]] が含まれていなければ、
ee を localExportEntries に追加する。
それ以外の場合、
ie を importEntries のうち [[LocalName]] が
ee .[[LocalName]]
である要素とする。
もし ie .[[ImportName]]
が namespace-object なら、
注: これはインポートされたモジュール名前空間オブジェクトの再エクスポートである。
ee を localExportEntries
に追加する。
それ以外の場合、
注: これは単一名称の再エクスポートである。
ExportEntry
Record { [[ModuleRequest]] :
ie .[[ModuleRequest]] , [[ImportName]] :
ie .[[ImportName]] , [[LocalName]] :
null , [[ExportName]] :
ee .[[ExportName]] } を
indirectExportEntries に追加する。
それ以外で ee .[[ImportName]] が
all-but-default なら、
Assert : ee .[[ExportName]] は null
である。
ee を starExportEntries に追加する。
それ以外の場合、
ee を indirectExportEntries に追加する。
async を body Contains
await とする。
以下を返す:ソーステキストモジュールレコード { [[Realm]] : realm , [[Environment]] : empty , [[Namespace]] : empty , [[CycleRoot]] : empty , [[HasTLA]] : async , [[AsyncEvaluationOrder]] : unset ,
[[TopLevelCapability]] : empty ,
[[AsyncParentModules]] : « », [[PendingAsyncDependencies]] :
empty , [[Status]] :
new , [[EvaluationError]] :
empty , [[HostDefined]] :
hostDefined , [[ECMAScriptCode]] :
body , [[Context]] :
empty , [[ImportMeta]] :
empty , [[RequestedModules]] :
requestedModules , [[LoadedModules]] : « »,
[[ImportEntries]] : importEntries , [[LocalExportEntries]] : localExportEntries ,
[[IndirectExportEntries]] :
indirectExportEntries , [[StarExportEntries]] : starExportEntries ,
[[DFSAncestorIndex]] : empty }。
注
実装は、ParseModule
の評価前にモジュールソーステキストを構文解析し、早期エラー条件を解析してもよい。ただし、エラーの報告は、この仕様が実際にそのソーステキストに対して
ParseModule を実行する時点まで遅延しなければならない。
16.2.1.7.2 モジュールレコード抽象メソッドの実装
以下は、ソーステキストモジュールレコード の具体メソッドであり、モジュールレコード の抽象メソッド(表44 で定義)を実装する。
16.2.1.7.2.1 GetExportedNames (
[exportStarSet ] )
ソーステキストモジュールレコード
module の GetExportedNames 具体メソッドは、オプション引数
exportStarSet (リスト で、ソーステキストモジュールレコード のリスト)を受け取り、文字列のリスト を返す。呼び出し時、以下の手順を実行する:
Assert : module .[[Status]] は new でない。
exportStarSet が未指定の場合、exportStarSet を新しい空のリスト に設定する。
もし exportStarSet に module が含まれていれば、
Assert :
export *の循環の起点に到達した。
新しい空のリスト を返す。
module を exportStarSet に追加する。
exportedNames を新しい空のリスト とする。
module .[[LocalExportEntries]] の各
ExportEntryレコード
e について、
Assert : module
はこのエクスポートの直接バインディングを提供する。
Assert : e .[[ExportName]] は null
でない。
e .[[ExportName]] を
exportedNames に追加する。
module .[[IndirectExportEntries]] の各
ExportEntryレコード
e について、
Assert : module
はこのエクスポートの特定バインディングをインポートする。
Assert : e .[[ExportName]] は null
でない。
e .[[ExportName]] を
exportedNames に追加する。
module .[[StarExportEntries]] の各
ExportEntryレコード
e について、
Assert : e .[[ModuleRequest]] は null
でない。
requestedModule を GetImportedModule (module ,
e .[[ModuleRequest]] ) とする。
starNames を
requestedModule .GetExportedNames(exportStarSet )
とする。
starNames の各要素 n について、
もし n が "default" でなければ、
もし exportedNames に n
が含まれていなければ、
n を exportedNames
に追加する。
exportedNames を返す。
注
GetExportedNames は、あいまいな star エクスポートバインディング名を除外したり、例外を投げたりしない。
16.2.1.7.2.2 ResolveExport ( exportName [ ,
resolveSet ] )
ソーステキストモジュールレコード
module の ResolveExport 具体メソッドは、引数 exportName (文字列)およびオプション引数
resolveSet (リスト で、Record 型、フィールド
[[Module]] (モジュールレコード )と
[[ExportName]] (文字列))を受け取り、ResolvedBindingレコード 、null 、または
ambiguous を返す。
ResolveExport
は、インポートされたバインディングを実際に定義するモジュールとローカルバインディング名へ解決しようとする。この定義モジュールは、このメソッドが呼び出されたモジュールレコード または、そのモジュールがインポートする他のモジュールである場合がある。resolveSet は、未解決の循環インポート/エクスポート経路を検出するために使われる。特定のモジュールレコード とexportName の組がresolveSet に既に存在する場合、インポート循環が発生したこととなる。再帰的にResolveExportを呼び出す前に、module とexportName のペアをresolveSet に追加する。
定義モジュールが見つかった場合、ResolvedBindingレコード { [[Module]] , [[BindingName]] }
が返る。このレコードは元々要求されたエクスポートの解決されたバインディングを示す。ただし、名前空間エクスポート(ローカルバインディングなし)の場合、[[BindingName]] はnamespace となる。定義が見つからないか循環が検出された場合はnull 、あいまいである場合はambiguous を返す。
呼び出し時、以下の手順を実行する:
Assert : module .[[Status]] は new でない。
resolveSet が未指定の場合、resolveSet を新しい空のリスト に設定する。
resolveSet の各 Record
{ [[Module]] , [[ExportName]] } r について、
もし module と r .[[Module]] が同じ モジュールレコード
であり、exportName が r .[[ExportName]] であれば、
Assert :
これは循環インポート要求である。
null を返す。
Record
{ [[Module]] : module , [[ExportName]] : exportName } を
resolveSet に追加する。
module .[[LocalExportEntries]] の各
ExportEntryレコード
e について、
もし e .[[ExportName]] が
exportName なら、
Assert :
module はこのエクスポートの直接バインディングを提供する。
ResolvedBindingレコード
{ [[Module]] : module ,
[[BindingName]] : e .[[LocalName]] } を返す。
module .[[IndirectExportEntries]] の各
ExportEntryレコード
e について、
もし e .[[ExportName]] が
exportName なら、
Assert :
e .[[ModuleRequest]] は
null ではない。
importedModule を GetImportedModule (module ,
e .[[ModuleRequest]] )
とする。
もし e .[[ImportName]] が
all なら、
Assert :
module はこのエクスポートの直接バインディングを提供しない。
ResolvedBindingレコード
{ [[Module]] :
importedModule , [[BindingName]] :
namespace } を返す。
それ以外の場合、
Assert :
module はこのエクスポートの特定バインディングをインポートする。
Assert :
e .[[ImportName]]
は 文字列 である。
importedModule .ResolveExport(e .[[ImportName]] ,
resolveSet ) を返す。
もし exportName が "default" なら、
Assert :
このモジュールによってdefaultエクスポートは明示的に定義されていない。
null を返す。
注: default エクスポートは export * from "mod"
宣言では提供できない。
starResolution を null とする。
module .[[StarExportEntries]] の各
ExportEntryレコード
e について、
Assert : e .[[ModuleRequest]] は null
ではない。
importedModule を GetImportedModule (module ,
e .[[ModuleRequest]] ) とする。
resolution を
importedModule .ResolveExport(exportName ,
resolveSet ) とする。
もし resolution が ambiguous
なら、ambiguous を返す。
もし resolution が null でなければ、
Assert :
resolution は ResolvedBindingレコード である。
もし starResolution が null なら、
starResolution を resolution
に設定する。
それ以外の場合、
Assert :
要求された名前を含む * インポートが複数存在する。
もし resolution .[[Module]] と
starResolution .[[Module]] が同じ モジュールレコード でないなら、ambiguous
を返す。
もし resolution .[[BindingName]] が
starResolution .[[BindingName]] でなく、かつ
resolution .[[BindingName]] または
starResolution .[[BindingName]] が
namespace
なら、ambiguous を返す。
もし resolution .[[BindingName]] が文字列 であり、starResolution .[[BindingName]] も文字列 であり、かつ両者が異なる場合、ambiguous
を返す。
starResolution を返す。
16.2.1.7.3 循環モジュールレコード抽象メソッドの実装
以下は、ソーステキストモジュールレコード の具体メソッドであり、循環モジュールレコード の抽象メソッド(表46 で定義)を実装する。
16.2.1.7.3.1 InitializeEnvironment ( )
ソーステキストモジュールレコード
module の InitializeEnvironment 具体メソッドは引数を受け取らず、unused
を含む正常完了 またはthrow
completion を返す。呼び出し時、以下の手順を実行する:
module .[[IndirectExportEntries]] の各
ExportEntryレコード
e について、
Assert : e .[[ExportName]] は null
ではない。
resolution を
module .ResolveExport(e .[[ExportName]] ) とする。
もし resolution が null または
ambiguous なら、SyntaxError
例外を投げる。
Assert : resolution
は ResolvedBindingレコード である。
Assert : module
の全ての名前付きエクスポートは解決可能である。
realm を module .[[Realm]] とする。
Assert : realm は
undefined ではない。
env を NewModuleEnvironment (realm .[[GlobalEnv]] ) とする。
module .[[Environment]] を env
に設定する。
module .[[ImportEntries]] の各 ImportEntryレコード
in について、
importedModule を GetImportedModule (module ,
in .[[ModuleRequest]] ) とする。
もし in .[[ImportName]] が
namespace-object なら、
namespace を GetModuleNamespace (importedModule )
とする。
! env .CreateImmutableBinding(in .[[LocalName]] ,
true ) を実行する。
! env .InitializeBinding(in .[[LocalName]] , namespace )
を実行する。
それ以外の場合、
resolution を
importedModule .ResolveExport(in .[[ImportName]] ) とする。
もし resolution が null または
ambiguous
なら、SyntaxError 例外を投げる。
もし resolution .[[BindingName]] が
namespace なら、
namespace を GetModuleNamespace (resolution .[[Module]] ) とする。
!
env .CreateImmutableBinding(in .[[LocalName]] ,
true ) を実行する。
!
env .InitializeBinding(in .[[LocalName]] ,
namespace ) を実行する。
それ以外の場合、
CreateImportBinding (env ,
in .[[LocalName]] ,
resolution .[[Module]] ,
resolution .[[BindingName]] ) を実行する。
moduleContext を新しい ECMAScriptコード実行コンテキスト とする。
moduleContext の Function を null に設定する。
Assert : module .[[Realm]] は undefined ではない。
moduleContext の Realm を module .[[Realm]] に設定する。
moduleContext の ScriptOrModule を module に設定する。
moduleContext の VariableEnvironment を module .[[Environment]] に設定する。
moduleContext の LexicalEnvironment を module .[[Environment]] に設定する。
moduleContext の PrivateEnvironment を null
に設定する。
module .[[Context]] を
moduleContext に設定する。
moduleContext を 実行コンテキストスタック にプッシュする。moduleContext
が実行中の実行コンテキスト となる。
code を module .[[ECMAScriptCode]] とする。
varDeclarations を VarScopedDeclarations (code )
とする。
declaredVarNames を新しい空のリスト とする。
varDeclarations の各要素 d について、
BoundNames (d )
の各要素 dn について、
もし declaredVarNames に dn が含まれていなければ、
! env .CreateMutableBinding(dn ,
false ) を実行する。
! env .InitializeBinding(dn ,
undefined ) を実行する。
dn を declaredVarNames に追加する。
lexDeclarations を LexicallyScopedDeclarations (code )
とする。
privateEnv を null とする。
lexDeclarations の各要素 d について、
BoundNames (d )
の各要素 dn について、
もし IsConstantDeclaration (d )
が true なら、
!
env .CreateImmutableBinding(dn ,
true ) を実行する。
それ以外の場合、
! env .CreateMutableBinding(dn ,
false ) を実行する。
もし d が FunctionDeclaration 、GeneratorDeclaration 、AsyncFunctionDeclaration 、または
AsyncGeneratorDeclaration
なら、
fo を InstantiateFunctionObject (d ,
env , privateEnv ) とする。
! env .InitializeBinding(dn ,
fo ) を実行する。
moduleContext を 実行コンテキストスタック から除去する。
unused を返す。
16.2.1.7.3.2 ExecuteModule ( [ capability ] )
ソーステキストモジュールレコード
module の ExecuteModule 具体メソッドは、オプション引数 capability (PromiseCapability
レコード )を受け取り、unused
を含む正常完了 またはthrow
completion を返す。呼び出し時、以下の手順を実行する:
moduleContext を新しい ECMAScriptコード実行コンテキスト とする。
moduleContext の Function を null に設定する。
moduleContext の Realm を module .[[Realm]] に設定する。
moduleContext の ScriptOrModule を module に設定する。
Assert : module
はリンク済みで、モジュール環境内の宣言もインスタンス化済みである。
moduleContext の VariableEnvironment を module .[[Environment]] に設定する。
moduleContext の LexicalEnvironment を module .[[Environment]] に設定する。
実行中の実行コンテキスト をサスペンドする。
もし module .[[HasTLA]] が
false なら、
Assert : capability
は未指定。
moduleContext を 実行コンテキストスタック にプッシュする。moduleContext
が実行中の実行コンテキスト となる。
result を Completion (Evaluation (module .[[ECMAScriptCode]] )) とする。
moduleContext をサスペンドし、実行コンテキストスタック から除去する。
スタック上のトップにあるコンテキストを実行中の実行コンテキスト として再開する。
もし result が abrupt
completion なら、
? result を返す。
それ以外の場合、
Assert : capability
は PromiseCapabilityレコード である。
AsyncBlockStart (capability ,
module .[[ECMAScriptCode]] ,
moduleContext ) を実行する。
unused を返す。
16.2.1.8 合成モジュールレコード
合成モジュールレコード は、仕様によって定義されたモジュールに関する情報を表現するために使用される。そのエクスポートされる名前は生成時に静的に定義されるが、対応する値はSetSyntheticModuleExport を使って時間の経過とともに変更できる。インポートや依存関係は持たない。
注
合成モジュールレコードは、さまざまな種類のモジュール(例:JSON モジュールや CSS モジュール)の定義に利用できる。
表43 で定義されているフィールドに加えて、合成モジュールレコードは表62 で記載されている追加フィールドを持つ。
表62: 合成モジュールレコード の追加フィールド
フィールド名
値の型
意味
[[ExportNames]]
文字列のリスト
モジュールのエクスポート名。このリストには重複が含まれない。
[[EvaluationSteps]]
抽象クロージャ
モジュール評価時に実行する初期化ロジック。合成モジュールレコード を唯一の引数として受け取る。[[ExportNames]] を変更してはならない。abrupt
completion を返すことがある。
16.2.1.8.1 CreateDefaultExportSyntheticModule
(defaultExport )
抽象操作 CreateDefaultExportSyntheticModule は、引数 defaultExport (ECMAScript
言語値 )を受け取り、合成モジュールレコード を返す。この操作はdefaultExport をデフォルトエクスポートとする合成モジュールレコード を生成する。呼び出し時、以下の手順を実行する:
realm を 現在の Realm レコード とする。
setDefaultExport を引数 (module ) を受け取り
defaultExport をキャプチャする新しい抽象クロージャ とし、呼び出し時に以下を実行する:
SetSyntheticModuleExport (module ,
"default" , defaultExport ) を実行する。
NormalCompletion (unused )
を返す。
以下を返す:合成モジュールレコード { [[Realm]] : realm , [[Environment]] : empty , [[Namespace]] : empty , [[HostDefined]] : undefined , [[ExportNames]] : « "default" », [[EvaluationSteps]] : setDefaultExport }。
16.2.1.8.2 ParseJSONModule ( source )
抽象操作 ParseJSONModule は、引数 source (文字列)を受け取り、正常完了( 合成モジュールレコード を含む)またはthrow
completion を返す。呼び出し時、以下の手順を実行する:
json を ? ParseJSON (source ) とする。
CreateDefaultExportSyntheticModule (json )
を返す。
16.2.1.8.3 SetSyntheticModuleExport ( module ,
exportName , exportValue )
抽象操作 SetSyntheticModuleExport は、引数 module (合成モジュールレコード )、exportName (文字列)、exportValue (ECMAScript
言語値 )を受け取りunused を返す。これは、既存の合成モジュールレコード のエクスポート値を設定/変更するために使用される。呼び出し時、以下の手順を実行する:
Assert :
module .[[ExportNames]] は
exportName を含む。
envRec を module .[[Environment]]
とする。
Assert :
envRec は empty ではない。
envRec .SetMutableBinding(exportName ,
exportValue , true ) を実行する。
unused を返す。
16.2.1.8.4 モジュールレコード抽象メソッドの実装
以下は、合成モジュールレコード の具体メソッドであり、モジュールレコード の抽象メソッド(表44 で定義)を実装する。
16.2.1.8.4.1 LoadRequestedModules ( )
合成モジュールレコード
module の LoadRequestedModules 具体メソッドは引数を受け取らず、Promise
を返す。呼び出し時、以下の手順を実行する:
! PromiseResolve (%Promise% ,
undefined ) を返す。
注
16.2.1.8.4.2 GetExportedNames ( )
合成モジュールレコード
module の GetExportedNames 具体メソッドは引数を受け取らず、文字列のリスト を返す。呼び出し時、以下の手順を実行する:
module .[[ExportNames]] を返す。
16.2.1.8.4.3 ResolveExport ( exportName )
合成モジュールレコード
module の ResolveExport 具体メソッドは引数
exportName (文字列)を受け取り、ResolvedBindingレコード またはnull を返す。呼び出し時、以下の手順を実行する:
もし module .[[ExportNames]] が
exportName を含まなければ、null を返す。
ResolvedBindingレコード {
[[Module]] : module , [[BindingName]] : exportName } を返す。
16.2.1.8.4.4 Link ( )
合成モジュールレコード
module の Link 具体メソッドは引数を受け取らず、unused
を含む正常完了 を返す。呼び出し時、以下の手順を実行する:
realm を module .[[Realm]] とする。
env を NewModuleEnvironment (realm .[[GlobalEnv]] ) とする。
module .[[Environment]] を env
に設定する。
module .[[ExportNames]] の各文字列
exportName について、
! env .CreateMutableBinding(exportName ,
false ) を実行する。
! env .InitializeBinding(exportName ,
undefined ) を実行する。
NormalCompletion (unused )
を返す。
16.2.1.8.4.5 Evaluate ( )
合成モジュールレコード
module の Evaluate 具体メソッドは引数を受け取らず、Promise を返す。呼び出し時、以下の手順を実行する:
moduleContext を新しい ECMAScriptコード実行コンテキスト とする。
moduleContext の Function を null に設定する。
moduleContext の Realm を module .[[Realm]] に設定する。
moduleContext の ScriptOrModule を module に設定する。
moduleContext の VariableEnvironment を module .[[Environment]] に設定する。
moduleContext の LexicalEnvironment を module .[[Environment]] に設定する。
実行中の実行コンテキスト をサスペンドする。
moduleContext を 実行コンテキストスタック にプッシュする。moduleContext
が実行中の実行コンテキスト となる。
steps を module .[[EvaluationSteps]] とする。
result を Completion (steps (module ))
とする。
moduleContext をサスペンドし、実行コンテキストスタック から除去する。
スタック上のトップにあるコンテキストを実行中の実行コンテキスト として再開する。
pc を ! NewPromiseCapability (%Promise% ) とする。
IfAbruptRejectPromise (result ,
pc ) を実行する。
! Call (pc .[[Resolve]] , undefined , «
undefined ») を実行する。
pc .[[Promise]] を返す。
16.2.1.9 GetImportedModule ( referrer ,
request )
抽象操作 GetImportedModule は、引数 referrer (循環モジュールレコード )と
request (ModuleRequestレコード )を受け取り、モジュールレコード を返す。呼び出し時、以下の手順を実行する:
records を リスト とし、referrer .[[LoadedModules]] の各 LoadedModuleRequestレコード
r について、ModuleRequestsEqual (r ,
request ) が true であるものを集める。
Assert :
records はちょうど 1 要素を持つ。これは、LoadRequestedModules が referrer
で正常に完了し、この抽象操作が呼ばれる前であるためである。
record を records の唯一の要素とする。
record .[[Module]] を返す。
16.2.1.10 HostLoadImportedModule ( referrer ,
moduleRequest , hostDefined , payload )
ホスト定義 抽象操作 HostLoadImportedModule は、引数
referrer (スクリプトレコード 、循環モジュールレコード 、または Realmレコード )、moduleRequest (ModuleRequestレコード )、hostDefined (任意)、payload (GraphLoadingStateレコード またはPromiseCapabilityレコード )を受け取り、unused を返す。
注1
referrer が Realmレコード となる例は、ウェブブラウザ ホスト である。例えば、ユーザーが以下のコントロールをクリックした場合:
<button type ="button" onclick ="import('./foo.mjs')" > Click me</button >
その時点で アクティブなスクリプトまたはモジュール は存在しない。より一般的には、これは
ホスト が 実行コンテキスト を、ScriptOrModule が
null の状態で 実行コンテキストスタック にプッシュする場合にも起こりうる。
HostLoadImportedModule の実装は、以下の要件に準拠しなければならない:
ホスト環境 は、FinishLoadingImportedModule (referrer ,
moduleRequest , payload , result )
を実行しなければならず、result はロード済み モジュールレコード を含む正常完了 またはthrow
completion のいずれかである(同期または非同期)。
この操作が、2つの (referrer , moduleRequest ) ペアで複数回呼ばれ、
最初の referrer が2つ目の referrer と同じであり、
ModuleRequestsEqual (最初の
moduleRequest , 2つ目の moduleRequest ) が
true である場合、
そして FinishLoadingImportedModule (referrer ,
moduleRequest , payload , result ) が 正常完了 で実行された場合、毎回同じ
result で FinishLoadingImportedModule を実行しなければならない。
もし moduleRequest .[[Attributes]] に
entry があり、entry .[[Key]] が
"type" かつ entry .[[Value]] が
"json" の場合、ホスト環境 は FinishLoadingImportedModule (referrer ,
moduleRequest , payload , result )
を実行する際、result は ParseJSONModule の呼び出しで返された
Completion
Record または throw
completion でなければならない。
この操作は payload を不透明値として扱い、FinishLoadingImportedModule へ渡す必要がある。
実際の処理はホスト定義 だが、通常は適切なモジュールレコード をロードするために必要なI/O処理を行う。異なる
(referrer , moduleRequest .[[Specifier]] ,
moduleRequest .[[Attributes]] ) の組は同じ モジュールレコード インスタンスにマップされる場合がある。実際のマッピングの意味論はホスト定義 だが、通常は
specifier の正規化処理が含まれる。典型的な正規化処理には、相対パスや省略パスの展開などが含まれる。
注2
上記の文は、ホスト が
type: "json" でインポートされた場合に JSON モジュールをサポートする必要がある(HostLoadImportedModule
が正常完了した場合)が、type: "json" なしでインポートした場合に JSON モジュールをサポートすることを禁じるものではない。
16.2.1.11 FinishLoadingImportedModule ( referrer ,
moduleRequest , payload , result )
抽象操作 FinishLoadingImportedModule は、引数 referrer (スクリプトレコード 、循環モジュールレコード 、または Realmレコード )、moduleRequest (ModuleRequestレコード )、payload (GraphLoadingStateレコード またはPromiseCapabilityレコード )、result (正常完了( モジュールレコード を含む)またはthrow
completion )を受け取り、unused を返す。呼び出し時、以下の手順を実行する:
もし result が 正常完了 であれば、
もし referrer .[[LoadedModules]] に
LoadedModuleRequestレコード
record があり、ModuleRequestsEqual (record ,
moduleRequest ) が true なら、
Assert : record .[[Module]] と result .[[Value]] は同じ モジュールレコード である。
それ以外の場合、
LoadedModuleRequestレコード
{ [[Specifier]] :
moduleRequest .[[Specifier]] ,
[[Attributes]] :
moduleRequest .[[Attributes]] ,
[[Module]] : result .[[Value]] } を referrer .[[LoadedModules]] に追加する。
もし payload が GraphLoadingStateレコード なら、
ContinueModuleLoading (payload ,
result ) を実行する。
それ以外の場合、
ContinueDynamicImport (payload ,
result ) を実行する。
unused を返す。
16.2.1.12 AllImportAttributesSupported ( attributes )
抽象操作 AllImportAttributesSupported は、引数 attributes (リスト で、ImportAttributeレコード のリスト)を受け取り、Boolean
を返す。呼び出し時、以下の手順を実行する:
supported を HostGetSupportedImportAttributes ()
とする。
attributes の各 ImportAttributeレコード
attribute について、
もし supported に attribute .[[Key]] が含まれていなければ、false を返す。
true を返す。
16.2.1.12.1 HostGetSupportedImportAttributes ( )
ホスト定義 抽象操作 HostGetSupportedImportAttributes
は引数を受け取らず、文字列のリスト を返す。これはホスト環境 がサポートするインポート属性を指定するために使われる。サポートされているキーを持つ属性のみがホスト に渡される。
HostGetSupportedImportAttributes の実装は、以下の要件に準拠しなければならない:
文字列のリスト を返すこと。各要素はサポートされる属性を示す。
この操作が呼ばれるたびに、同じ順序で同じ内容のリスト を返さなければならない。
HostGetSupportedImportAttributes のデフォルト実装は、新しい空のリスト を返すことである。
注
サポートされるインポート属性を
ホスト が指定し、すべての属性をホストに渡してからホストが処理するものを選択するのではなく、サポートされていない属性が異なる
ホスト 間で一貫して扱われるようにすることが目的である。
16.2.1.13 GetModuleNamespace ( module )
抽象操作 GetModuleNamespace は、引数 module (モジュールレコード の具象サブクラスのインスタンス)を受け取り、モジュール名前空間オブジェクトを返す。これはmodule のエクスポートを表すモジュール名前空間オブジェクトを取得し、初めて要求された時に遅延生成し、以降はmodule .[[Namespace]] に保存して再利用する。呼び出し時、以下の手順を実行する:
Assert :
module が 循環モジュールレコード の場合、module .[[Status]] は new または
unlinked でない。
namespace を module .[[Namespace]] とする。
もし namespace が empty なら、
exportedNames を module .GetExportedNames() とする。
unambiguousNames を新しい空のリスト とする。
exportedNames の各要素 name について、
resolution を
module .ResolveExport(name ) とする。
もし resolution が ResolvedBindingレコード であれば、name
を unambiguousNames に追加する。
namespace を ModuleNamespaceCreate (module ,
unambiguousNames ) に設定する。
namespace を返す。
注
GetModuleNamespace
は決して例外を投げない。この時点で解決できない名前は単に名前空間から除外される。これらは後で本当のリンクエラーにつながるが、すべてが明示的に要求されていない曖昧な
star エクスポートのみの場合は除外される。
16.2.1.14 実行時意味論: Evaluation
Module : [empty]
undefined を返す。
ModuleBody : ModuleItemList
result を Completion (Evaluation (ModuleItemList )) とする。
もし result が 正常完了 であり、result .[[Value]] が empty なら、
undefined を返す。
? result を返す。
ModuleItemList :
ModuleItemList
ModuleItem
sl を ? Evaluation (ModuleItemList ) とする。
s を Completion (Evaluation (ModuleItem )) とする。
? UpdateEmpty (s ,
sl ) を返す。
注
ModuleItem : ImportDeclaration
empty を返す。
16.2.2 インポート
構文
ImportDeclaration
:
import
ImportClause
FromClause
WithClause opt
;
import
ModuleSpecifier
WithClause opt
;
ImportClause
:
ImportedDefaultBinding
NameSpaceImport
NamedImports
ImportedDefaultBinding
,
NameSpaceImport
ImportedDefaultBinding
,
NamedImports
ImportedDefaultBinding
:
ImportedBinding
NameSpaceImport
:
*
as
ImportedBinding
NamedImports
:
{
}
{
ImportsList
}
{
ImportsList
,
}
FromClause
:
from
ModuleSpecifier
ImportsList
:
ImportSpecifier
ImportsList
,
ImportSpecifier
ImportSpecifier
:
ImportedBinding
ModuleExportName
as
ImportedBinding
ModuleSpecifier
:
StringLiteral
ImportedBinding
:
BindingIdentifier [~Yield,
+Await]
WithClause
:
with
{
}
with
{
WithEntries
,opt
}
WithEntries
:
AttributeKey
:
StringLiteral
AttributeKey
:
StringLiteral
,
WithEntries
AttributeKey
:
IdentifierName
StringLiteral
16.2.2.1 静的意味論: 早期エラー
ModuleItem
:
ImportDeclaration
WithClause
:
with
{
WithEntries
,opt
}
16.2.2.2 静的意味論: ImportEntries
構文指示操作
ImportEntries は引数を取らず、リスト 型の
ImportEntry レコード のリストを返す。
以下の生成規則ごとに定義される:
Module
:
[empty]
新しい空の リスト を返す。
ModuleItemList
:
ModuleItemList
ModuleItem
entries1 を ModuleItemList の
ImportEntries とする。
entries2 を ModuleItem の
ImportEntries とする。
entries1 と entries2 の リスト連結 を返す。
ModuleItem
:
ExportDeclaration
StatementListItem
新しい空の リスト を返す。
ImportDeclaration
:
import
ImportClause
FromClause
WithClause opt
;
module を ImportDeclaration の
ModuleRequests
の唯一の要素とする。
ImportClause の
ImportEntriesForModule
に引数 module を渡して返す。
ImportDeclaration
:
import
ModuleSpecifier
WithClause opt
;
新しい空の リスト を返す。
16.2.2.3 静的意味論: ImportEntriesForModule
構文指示操作
ImportEntriesForModule は、引数 module (ModuleRequest
Record )を受け取り、
リスト 型の
ImportEntry レコード のリストを返す。
以下の生成規則ごとに定義される:
ImportClause :
ImportedDefaultBinding
,
NameSpaceImport
entries1 を ImportedDefaultBinding の
ImportEntriesForModule
(引数 module )とする。
entries2 を NameSpaceImport の
ImportEntriesForModule
(引数 module )とする。
entries1 と entries2 の リスト連結 を返す。
ImportClause :
ImportedDefaultBinding
,
NamedImports
entries1 を ImportedDefaultBinding の
ImportEntriesForModule
(引数 module )とする。
entries2 を NamedImports の
ImportEntriesForModule
(引数 module )とする。
entries1 と entries2 の リスト連結 を返す。
ImportedDefaultBinding
: ImportedBinding
localName を ImportedBinding の
BoundNames の唯一の要素とする。
defaultEntry を ImportEntry Record
{ [[ModuleRequest]] : module , [[ImportName]] : "default" , [[LocalName]] : localName } とする。
« defaultEntry » を返す。
NameSpaceImport
:
*
as
ImportedBinding
localName を ImportedBinding の
StringValue とする。
entry を ImportEntry Record
{ [[ModuleRequest]] : module , [[ImportName]] : namespace-object ,
[[LocalName]] : localName } とする。
« entry » を返す。
NamedImports :
{
}
新しい空の リスト を返す。
ImportsList :
ImportsList
,
ImportSpecifier
specs1 を ImportsList の
ImportEntriesForModule
(引数 module )とする。
specs2 を ImportSpecifier の
ImportEntriesForModule
(引数 module )とする。
specs1 と specs2 の リスト連結 を返す。
ImportSpecifier
: ImportedBinding
localName を ImportedBinding の
BoundNames の唯一の要素とする。
entry を ImportEntry Record
{ [[ModuleRequest]] : module , [[ImportName]] : localName , [[LocalName]] : localName } とする。
« entry » を返す。
ImportSpecifier
:
ModuleExportName
as
ImportedBinding
importName を ModuleExportName の
StringValue とする。
localName を ImportedBinding の
StringValue とする。
entry を ImportEntry Record
{ [[ModuleRequest]] : module , [[ImportName]] : importName , [[LocalName]] : localName } とする。
« entry » を返す。
16.2.2.4 静的意味論: WithClauseToAttributes
構文指示操作
WithClauseToAttributes は引数を取らず、
リスト 型の
ImportAttribute レコード のリストを返す。
以下の生成規則ごとに定義される:
WithClause :
with
{
}
新しい空の リスト を返す。
WithClause :
with
{
WithEntries
,opt
}
attributes を WithEntries の WithClauseToAttributes
とする。
attributes の [[Key]]
フィールドの値をUTF-16コード単位値の列として扱い、辞書式順序でソートする。注: このソートは、ホスト が属性の列挙順に基づいて動作を変更することを禁止する点でのみ観察可能である。
attributes を返す。
WithEntries :
AttributeKey
:
StringLiteral
key を AttributeKey の PropName とする。
entry を ImportAttribute Record { [[Key]] : key , [[Value]] :
StringLiteral の
SV } とする。
« entry » を返す。
WithEntries :
AttributeKey
:
StringLiteral
,
WithEntries
key を AttributeKey の PropName とする。
entry を ImportAttribute Record { [[Key]] : key , [[Value]] :
StringLiteral の
SV } とする。
rest を WithEntries の WithClauseToAttributes
とする。
« entry » と rest の リスト連結 を返す。
16.2.3 エクスポート
構文
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
export
VariableStatement [~Yield,
+Await]
export
Declaration [~Yield,
+Await]
export
default
HoistableDeclaration [~Yield,
+Await, +Default]
export
default
ClassDeclaration [~Yield,
+Await, +Default]
export
default
[lookahead ∉ { function , async
[no LineTerminator here]
function , class }]
AssignmentExpression [+In,
~Yield, +Await]
;
ExportFromClause :
*
*
as
ModuleExportName
NamedExports
NamedExports :
{
}
{
ExportsList
}
{
ExportsList
,
}
ExportsList :
ExportSpecifier
ExportsList
,
ExportSpecifier
ExportSpecifier :
ModuleExportName
ModuleExportName
as
ModuleExportName
16.2.3.1 静的意味論: 早期エラー
ExportDeclaration
:
export
NamedExports
;
注
16.2.3.2 静的意味論: ExportedBindings
構文指示操作
ExportedBindings は引数を取らず、リスト 型の文字列リストを返す。
注
ExportedBindingsは、Module
の
ExportedNames
に明示的に関連付けられたローカルに束縛された名前である。
以下の生成規則ごとに定義される:
ModuleItemList :
ModuleItemList
ModuleItem
names1 を ModuleItemList の
ExportedBindings
とする。
names2 を ModuleItem の
ExportedBindings
とする。
names1 と names2 の リスト連結 を返す。
ModuleItem :
ImportDeclaration
StatementListItem
新しい空の リスト を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
新しい空の リスト を返す。
ExportDeclaration
:
export
NamedExports
;
NamedExports の
ExportedBindings
を返す。
ExportDeclaration
:
export
VariableStatement
VariableStatement の
BoundNames を返す。
ExportDeclaration
:
export
Declaration
Declaration の
BoundNames を返す。
ExportDeclaration
:
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
この ExportDeclaration の
BoundNames を返す。
NamedExports :
{
}
新しい空の リスト を返す。
ExportsList :
ExportsList
,
ExportSpecifier
names1 を ExportsList の
ExportedBindings
とする。
names2 を ExportSpecifier の
ExportedBindings
とする。
names1 と names2 の リスト連結 を返す。
ExportSpecifier
: ModuleExportName
ModuleExportName の
StringValue
を唯一の要素とする
リスト を返す。
ExportSpecifier
:
ModuleExportName
as
ModuleExportName
最初の ModuleExportName の
StringValue
を唯一の要素とする
リスト を返す。
16.2.3.3 静的意味論: ExportedNames
構文指示操作
ExportedNames は引数を取らず、リスト 型の文字列を返す。
注
ExportedNamesは、Module
が自身のローカルの名前束縛のいずれかに明示的にマッピングした外部から見える名前である。
以下の生成規則ごとに定義される:
ModuleItemList :
ModuleItemList
ModuleItem
names1 を ModuleItemList の
ExportedNames とする。
names2 を ModuleItem の
ExportedNames とする。
names1 と names2 の リスト連結 を返す。
ModuleItem : ExportDeclaration
ExportDeclaration の
ExportedNames を返す。
ModuleItem :
ImportDeclaration
StatementListItem
新しい空の リスト を返す。
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
ExportFromClause の
ExportedNames を返す。
ExportFromClause
: *
新しい空の リスト を返す。
ExportFromClause
:
*
as
ModuleExportName
ModuleExportName の
StringValue
を唯一の要素とする
リスト を返す。
ExportFromClause
: NamedExports
NamedExports の
ExportedNames を返す。
ExportDeclaration
:
export
VariableStatement
VariableStatement の
BoundNames を返す。
ExportDeclaration
:
export
Declaration
Declaration の
BoundNames を返す。
ExportDeclaration
:
export
default
HoistableDeclaration
export
default
ClassDeclaration
export
default
AssignmentExpression
;
« "default" » を返す。
NamedExports :
{
}
新しい空の リスト を返す。
ExportsList :
ExportsList
,
ExportSpecifier
names1 を ExportsList の
ExportedNames とする。
names2 を ExportSpecifier の
ExportedNames とする。
names1 と names2 の リスト連結 を返す。
ExportSpecifier
: ModuleExportName
ModuleExportName の
StringValue
を唯一の要素とする
リスト を返す。
ExportSpecifier
:
ModuleExportName
as
ModuleExportName
2番目の ModuleExportName の
StringValue
を唯一の要素とする
リスト を返す。
16.2.3.4 Static Semantics: ExportEntries
The syntax-directed
operation ExportEntries takes no arguments and returns a List of ExportEntry
Records . It is defined piecewise over the following productions:
Module : [empty]
Return a new empty List .
ModuleItemList :
ModuleItemList
ModuleItem
Let entries1 be the ExportEntries of
ModuleItemList .
Let entries2 be the ExportEntries of
ModuleItem .
Return the list-concatenation of
entries1 and entries2 .
ModuleItem :
ImportDeclaration
StatementListItem
Return a new empty List .
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
Let module be the sole element of the ModuleRequests of
ExportDeclaration .
Return the ExportEntriesForModule
of ExportFromClause with argument
module .
ExportDeclaration
:
export
NamedExports
;
Return the ExportEntriesForModule
of NamedExports
with argument null .
ExportDeclaration
:
export
VariableStatement
Let entries be a new empty List .
Let names be the BoundNames of VariableStatement .
For each element name of names , do
Append the ExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : name , [[ExportName]] : name } to
entries .
Return entries .
ExportDeclaration
:
export
Declaration
Let entries be a new empty List .
Let names be the BoundNames of Declaration .
For each element name of names , do
Append the ExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : name , [[ExportName]] : name } to
entries .
Return entries .
ExportDeclaration
:
export
default
HoistableDeclaration
Let names be the BoundNames of HoistableDeclaration .
Let localName be the sole element of names .
Return a List whose
sole element is a new ExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : localName , [[ExportName]] : "default" }.
ExportDeclaration
:
export
default
ClassDeclaration
Let names be the BoundNames of ClassDeclaration .
Let localName be the sole element of names .
Return a List whose
sole element is a new ExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : localName , [[ExportName]] : "default" }.
ExportDeclaration
:
export
default
AssignmentExpression
;
Let entry be the ExportEntry Record { [[ModuleRequest]] : null , [[ImportName]] : null , [[LocalName]] : "*default*" , [[ExportName]] : "default" }.
Return « entry ».
Note
"*default*" is used within this specification as a synthetic name
for anonymous default export values. See this note for
more details.
16.2.3.5 Static Semantics: ExportEntriesForModule
The syntax-directed
operation ExportEntriesForModule takes argument module (a
ModuleRequest Record or
null ) and returns a List of ExportEntry
Records . It is defined piecewise over the following productions:
ExportFromClause
: *
Let entry be the ExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : all-but-default , [[LocalName]] : null , [[ExportName]] : null }.
Return « entry ».
ExportFromClause
:
*
as
ModuleExportName
Let exportName be the StringValue of
ModuleExportName .
Let entry be the ExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : all , [[LocalName]] : null , [[ExportName]] : exportName }.
Return « entry ».
NamedExports :
{
}
Return a new empty List .
ExportsList :
ExportsList
,
ExportSpecifier
Let specs1 be the ExportEntriesForModule
of ExportsList with
argument module .
Let specs2 be the ExportEntriesForModule
of ExportSpecifier with argument
module .
Return the list-concatenation of
specs1 and specs2 .
ExportSpecifier
: ModuleExportName
Let sourceName be the StringValue of
ModuleExportName .
If module is null , then
Let localName be sourceName .
Let importName be null .
Else,
Let localName be null .
Let importName be sourceName .
Return a List whose
sole element is a new ExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : importName , [[LocalName]] : localName , [[ExportName]] : sourceName }.
ExportSpecifier
:
ModuleExportName
as
ModuleExportName
Let sourceName be the StringValue of the
first ModuleExportName .
Let exportName be the StringValue of the
second ModuleExportName .
If module is null , then
Let localName be sourceName .
Let importName be null .
Else,
Let localName be null .
Let importName be sourceName .
Return a List whose
sole element is a new ExportEntry Record { [[ModuleRequest]] : module , [[ImportName]] : importName , [[LocalName]] : localName , [[ExportName]] : exportName }.
16.2.3.6 Static Semantics: ReferencedBindings
The syntax-directed
operation ReferencedBindings takes no arguments and returns a
List of Parse
Nodes . It is defined piecewise over the following productions:
NamedExports :
{
}
Return a new empty List .
ExportsList :
ExportsList
,
ExportSpecifier
Let names1 be the ReferencedBindings
of ExportsList .
Let names2 be the ReferencedBindings
of ExportSpecifier .
Return the list-concatenation of
names1 and names2 .
ExportSpecifier
:
ModuleExportName
as
ModuleExportName
Return the ReferencedBindings
of the first ModuleExportName .
ModuleExportName
: IdentifierName
Return a List whose
sole element is the IdentifierName .
ModuleExportName
: StringLiteral
Return a List whose
sole element is the StringLiteral .
16.2.3.7 Runtime Semantics: Evaluation
ExportDeclaration
:
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
Return empty .
ExportDeclaration
:
export
VariableStatement
Return ? Evaluation of VariableStatement .
ExportDeclaration
:
export
Declaration
Return ? Evaluation of Declaration .
ExportDeclaration
:
export
default
HoistableDeclaration
Return ? Evaluation of HoistableDeclaration .
ExportDeclaration
:
export
default
ClassDeclaration
Let value be ? BindingClassDeclarationEvaluation of
ClassDeclaration .
Let className be the sole element of the BoundNames of ClassDeclaration .
If className is "*default*" , then
Let env be the running execution
context 's LexicalEnvironment.
Perform ? InitializeBoundName ("*default*" ,
value , env ).
Return empty .
ExportDeclaration
:
export
default
AssignmentExpression
;
If IsAnonymousFunctionDefinition (AssignmentExpression ) is
true , then
Let value be ? NamedEvaluation of AssignmentExpression
with argument "default" .
Else,
Let rhs be ? Evaluation
of AssignmentExpression .
Let value be ? GetValue (rhs ).
Let env be the running execution
context 's LexicalEnvironment.
Perform ? InitializeBoundName ("*default*" ,
value , env ).
Return empty .
17 Error Handling and Language Extensions
An implementation must report most errors at the time the relevant ECMAScript language construct is
evaluated. An early error is an error
that can be detected and reported prior to the evaluation of any construct in the Script containing the error. The presence of an
early error prevents
the evaluation of the construct. An implementation must report early errors in a Script as part of parsing that Script in ParseScript . Early errors in a Module are reported at the point when the Module would be evaluated and the Module is never initialized. Early errors in eval
code are reported at the time eval is called and prevent evaluation of the eval
code. All errors that are not early
errors are runtime errors.
An implementation must report as an early error any occurrence of a condition that is listed in a
“Static Semantics: Early Errors” subclause of this specification.
An implementation shall not treat other kinds of errors as early errors even if the compiler can prove
that a construct cannot execute without error under any circumstances. An implementation may issue an
early warning in such a case, but it should not report the error until the relevant construct is
actually executed.
An implementation shall report all errors as specified, except for the following:
Except as restricted in 17.1 , a host or implementation may extend Script syntax, Module syntax, and regular expression pattern or flag
syntax. To permit this, all operations (such as calling eval, using a regular
expression literal, or using the Function or RegExp constructor ) that are allowed to throw
SyntaxError are permitted to exhibit host-defined behaviour instead of throwing
SyntaxError when they encounter a host-defined extension to the script
syntax or regular expression pattern or flag syntax.
Except as restricted in 17.1 , a host or implementation may provide additional
types, values, objects, properties, and functions beyond those described in this specification. This
may cause constructs (such as looking up a variable in the global scope) to have host-defined
behaviour instead of throwing an error (such as ReferenceError ).
17.1 Forbidden Extensions
An implementation must not extend this specification in the following ways:
ECMAScript function
objects defined using syntactic constructors in strict mode
code must not be created with own properties named
"caller" or "arguments" . Such own properties also must not
be created for function objects defined using an ArrowFunction , MethodDefinition , GeneratorDeclaration ,
GeneratorExpression ,
AsyncGeneratorDeclaration , AsyncGeneratorExpression , ClassDeclaration , ClassExpression , AsyncFunctionDeclaration , AsyncFunctionExpression , or AsyncArrowFunction
regardless of whether the definition is contained in strict mode code . Built-in
functions, strict
functions created using the Function constructor , generator functions
created using the Generator constructor , async functions created using the
AsyncFunction constructor , and functions created using the
bind method also must not be created with such own properties.
If an implementation extends any function object with an own property named
"caller" the value of that property, as observed using [[Get]] or [[GetOwnProperty]] , must not be a
strict
function object. If it is an accessor property , the function
that is the value of the property's [[Get]] attribute must never return
a strict
function when called.
Neither mapped nor unmapped arguments objects may be created with an own property named
"caller" .
The behaviour of built-in methods which are specified in ECMA-402, such as those named
toLocaleString, must not be extended except as specified in ECMA-402.
The RegExp pattern grammars in 22.2.1 and B.1.2 must not be extended to
recognize any of the source characters A-Z or a-z as IdentityEscape [+UnicodeMode]
when the [UnicodeMode] grammar parameter is present.
The Syntactic Grammar must not be extended in any manner that allows the token : to
immediately follow source text that is matched by the BindingIdentifier nonterminal symbol.
When processing strict mode code , an implementation must not
relax the early
error rules of 12.9.3.1 .
TemplateEscapeSequence must not be
extended to include LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence as
defined in 12.9.4 .
When processing strict mode code , the extensions defined in
B.3.1 , B.3.2 ,
B.3.3 ,
and B.3.5 must not be
supported.
When parsing for the Module
goal symbol , the lexical grammar
extensions defined in B.1.1 must not be supported.
ImportCall must not be extended.
18 ECMAScript Standard Built-in Objects
There are certain built-in objects available whenever an ECMAScript Script or Module begins execution. One, the global object ,
is part of the global environment of the executing program. Others are accessible as initial properties
of the global
object or indirectly as properties of accessible built-in objects.
Unless specified otherwise, a built-in object that is callable as a function is a built-in function object
with the characteristics described in 10.3 . Unless specified otherwise, the [[Extensible]] internal slot of a built-in object initially has the value
true . Every built-in function object has a [[Realm]]
internal slot whose value is the Realm Record of the realm for which the object was initially created.
Many built-in objects are functions: they can be invoked with arguments. Some of them furthermore are
constructors : they
are functions intended for use with the new operator. For each built-in function, this
specification describes the arguments required by that function and the properties of that function object .
For each built-in constructor , this specification furthermore describes
properties of the prototype object of that constructor and properties of specific object instances
returned by a new expression that invokes that constructor .
Unless otherwise specified in the description of a particular function, if a built-in function or
constructor is given
fewer arguments than the function is specified to require, the function or constructor shall behave exactly as if it had
been given sufficient additional arguments, each such argument being the undefined
value. Such missing arguments are considered to be “not present” and may be identified in that manner by
specification algorithms. In the description of a particular function, the terms
“this value” and “NewTarget” have the meanings given in 10.3 .
Unless otherwise specified in the description of a particular function, if a built-in function or
constructor described
is given more arguments than the function is specified to allow, the extra arguments are evaluated by
the call and then ignored by the function. However, an implementation may define implementation specific
behaviour relating to such arguments as long as the behaviour is not the throwing of a
TypeError exception that is predicated simply on the presence of an extra argument.
Note 1
Implementations that add additional capabilities to the set of built-in functions are encouraged
to do so by adding new functions rather than adding new parameters to existing functions.
Unless otherwise specified every built-in function and every built-in constructor has the Function prototype
object , which is the initial value of the expression
Function.prototype (20.2.3 ), as
the value of its [[Prototype]] internal slot.
Unless otherwise specified every built-in prototype object has the Object prototype object ,
which is the initial value of the expression Object.prototype (20.1.3 ), as the value of
its [[Prototype]] internal slot, except the Object prototype object
itself.
If this specification defines a built-in constructor 's behaviour via algorithm steps, then that is its
behaviour for the purposes of both [[Call]] and [[Construct]] . If such an algorithm needs to distinguish the two cases, it
checks whether NewTarget is undefined , which indicates a [[Call]] invocation.
Built-in function
objects that are not identified as constructors do not implement the [[Construct]] internal method unless otherwise specified in the description of a
particular function.
Built-in function
objects that are not constructors do not have a "prototype"
property unless otherwise specified in the description of a particular function.
Each built-in function defined in this specification is created by calling the CreateBuiltinFunction abstract operation
(10.3.4 ). The values of the length
and name parameters are the initial values of the "length" and
"name" properties as discussed below. The values of the prefix parameter
are similarly discussed below.
Every built-in function
object , including constructors , has a "length" property
whose value is a non-negative integral Number . Unless otherwise specified, this value
is the number of required parameters shown in the subclause heading for the function description.
Optional parameters and rest parameters are not included in the parameter count.
Note 2
For example, the function object that is the initial value of the
"map" property of the Array prototype
object is described under the subclause heading «Array.prototype.map
(callback [ , thisArg])» which shows the two named arguments callback and thisArg, the latter
being optional; therefore the value of the "length" property of that
function
object is 1 𝔽 .
Unless otherwise specified, the "length" property of a built-in function object has
the attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }.
Every built-in function
object , including constructors , has a "name" property whose
value is a String . Unless otherwise
specified, this value is the name that is given to the function in this specification. Functions that
are identified as anonymous functions use the empty String as the value of the "name"
property. For functions that are specified as properties of objects, the name value is the property name string
used to access the function. Functions that are specified as get or set accessor functions of built-in
properties have "get" or "set" (respectively) passed to the
prefix parameter when calling CreateBuiltinFunction .
The value of the "name" property is explicitly specified for each built-in functions
whose property key
is a Symbol value. If such an
explicitly specified value starts with the prefix "get " or "set "
and the function for which it is specified is a get or set accessor function of a built-in property, the
value without the prefix is passed to the name parameter, and the value
"get" or "set" (respectively) is passed to the prefix
parameter when calling CreateBuiltinFunction .
Unless otherwise specified, the "name" property of a built-in function object has
the attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }.
Every other data
property described in clauses 19 through 28 and in Annex
B.2 has the attributes { [[Writable]] : true , [[Enumerable]] :
false , [[Configurable]] : true } unless
otherwise specified.
Every accessor
property described in clauses 19 through 28 and in Annex
B.2 has the attributes { [[Enumerable]] : false , [[Configurable]] : true } unless otherwise specified. If only
a get accessor function is described, the set accessor function is the default value,
undefined . If only a set accessor is described the get accessor is the default value,
undefined .
19 The Global Object
The global object :
is created before control enters any execution context .
does not have a [[Construct]] internal method; it cannot be used as a
constructor with
the new operator.
does not have a [[Call]] internal method; it cannot be invoked as a
function.
has a [[Prototype]] internal slot whose value is host-defined .
may have host-defined properties in addition to the properties
defined in this specification. This may include a property whose value is the global object itself.
19.1 Value Properties of the Global Object
19.1.1 globalThis
The initial value of the "globalThis" property of the global
object in a Realm Record realm is
realm .[[GlobalEnv]] .[[GlobalThisValue]] .
This property has the attributes { [[Writable]] :
true , [[Enumerable]] : false , [[Configurable]] : true }.
19.1.2 Infinity
The value of Infinity is +∞ 𝔽 (see 6.1.6.1 ). This property
has the attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }.
19.1.3 NaN
The value of NaN is NaN (see 6.1.6.1 ). This property
has the attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }.
19.1.4 undefined
The value of undefined is undefined (see 6.1.1 ). This
property has the attributes { [[Writable]] : false ,
[[Enumerable]] : false , [[Configurable]] : false }.
19.2 Function Properties of the Global Object
19.2.1 eval ( x )
This function is the %eval% intrinsic object.
It performs the following steps when called:
Return ? PerformEval (x ,
false , false ).
19.2.1.1 PerformEval ( x , strictCaller ,
direct )
The abstract operation PerformEval takes arguments x (an ECMAScript language value ),
strictCaller (a Boolean), and direct (a Boolean) and returns either a
normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Assert : If
direct is false , then strictCaller is also
false .
If x is not a
String , return x .
Let evalRealm be the current Realm Record .
NOTE: In the case of a direct
eval , evalRealm is the realm of both the caller of
eval and of the eval function itself.
Perform ? HostEnsureCanCompileStrings (evalRealm ,
« », x , direct ).
Let inFunction be false .
Let inMethod be false .
Let inDerivedConstructor be false .
Let inClassFieldInitializer be false .
If direct is true , then
Let thisEnvRec be GetThisEnvironment ().
If thisEnvRec is a Function Environment
Record , then
Let F be thisEnvRec .[[FunctionObject]] .
Set inFunction to true .
Set inMethod to thisEnvRec .HasSuperBinding().
If F .[[ConstructorKind]] is
derived , set inDerivedConstructor
to true .
Let classFieldInitializerName be F .[[ClassFieldInitializerName]] .
If classFieldInitializerName is not
empty , set inClassFieldInitializer
to true .
Perform the following substeps in an implementation-defined order,
possibly interleaving parsing and error detection:
Let script be ParseText (x , Script ).
If script is a List
of errors, throw a SyntaxError exception.
If script Contains
ScriptBody
is false , return undefined .
Let body be the ScriptBody of
script .
If inFunction is false and body
Contains
NewTarget ,
throw a SyntaxError exception.
If inMethod is false and body
Contains
SuperProperty , throw a
SyntaxError exception.
If inDerivedConstructor is false and
body Contains
SuperCall ,
throw a SyntaxError exception.
If inClassFieldInitializer is true and
ContainsArguments
of body is true , throw a
SyntaxError exception.
If strictCaller is true , let strictEval be
true .
Else, let strictEval be ScriptIsStrict of
script .
Let runningContext be the running execution
context .
NOTE: If direct is true , runningContext
will be the execution context that
performed the direct
eval . If direct is false ,
runningContext will be the execution
context for the invocation of the eval function.
If direct is true , then
Let lexEnv be NewDeclarativeEnvironment (runningContext 's
LexicalEnvironment).
Let varEnv be runningContext 's VariableEnvironment.
Let privateEnv be runningContext 's PrivateEnvironment.
Else,
Let lexEnv be NewDeclarativeEnvironment (evalRealm .[[GlobalEnv]] ).
Let varEnv be evalRealm .[[GlobalEnv]] .
Let privateEnv be null .
If strictEval is true , set varEnv to
lexEnv .
If runningContext is not already suspended, suspend
runningContext .
Let evalContext be a new ECMAScript code execution
context .
Set evalContext 's Function to null .
Set evalContext 's Realm to evalRealm .
Set evalContext 's ScriptOrModule to runningContext 's
ScriptOrModule.
Set evalContext 's VariableEnvironment to varEnv .
Set evalContext 's LexicalEnvironment to lexEnv .
Set evalContext 's PrivateEnvironment to privateEnv .
Push evalContext onto the execution context
stack ; evalContext is now the running execution context .
Let result be Completion (EvalDeclarationInstantiation (body ,
varEnv , lexEnv , privateEnv ,
strictEval )).
If result is a normal
completion , then
Set result to Completion (Evaluation of body ).
If result is a normal
completion and result .[[Value]] is empty , then
Set result to NormalCompletion (undefined ).
Suspend evalContext and remove it from the execution context stack .
Resume the context that is now on the top of the execution context stack as
the running execution context .
Return ? result .
Note
The eval code cannot instantiate variable or function bindings in the variable
environment of the calling context that invoked the eval if either the code of the
calling context or the eval code is strict mode code .
Instead such bindings are instantiated in a new VariableEnvironment that is only
accessible to the eval code. Bindings introduced by let,
const, or class declarations are always instantiated in a
new LexicalEnvironment.
19.2.1.2 HostEnsureCanCompileStrings ( calleeRealm ,
parameterStrings , bodyString , direct )
The host-defined abstract operation
HostEnsureCanCompileStrings takes arguments calleeRealm (a Realm
Record ), parameterStrings (a List of Strings),
bodyString (a String), and direct (a Boolean) and returns either a
normal completion
containing unused or a throw completion . It
allows host
environments to block certain ECMAScript functions which allow
developers to interpret and evaluate strings as ECMAScript code.
parameterStrings represents the strings that, when using one of the function
constructors , will be concatenated together to
build the parameters list. bodyString represents the function body or the string
passed to an eval call.
direct signifies whether the evaluation is a direct eval .
The default implementation of HostEnsureCanCompileStrings is to return NormalCompletion (unused ).
19.2.1.3 EvalDeclarationInstantiation ( body ,
varEnv , lexEnv , privateEnv , strict )
The abstract operation EvalDeclarationInstantiation takes arguments body (a
ScriptBody Parse
Node ), varEnv (an Environment Record ),
lexEnv (a Declarative Environment
Record ), privateEnv (a PrivateEnvironment Record or
null ), and strict (a Boolean) and returns either a normal completion
containing unused or a throw completion . It
performs the following steps when called:
Let varNames be the VarDeclaredNames
of body .
Let varDeclarations be the VarScopedDeclarations
of body .
If strict is false , then
If varEnv is a Global
Environment Record , then
For each element name of varNames , do
If HasLexicalDeclaration (varEnv ,
name ) is true , throw a
SyntaxError exception.
NOTE: eval will not create a global var
declaration that would be shadowed by a global lexical
declaration.
Let thisEnv be lexEnv .
Assert : The following loop will
terminate.
Repeat, while thisEnv and varEnv are not the same
Environment Record ,
If thisEnv is not an
Object Environment
Record , then
NOTE: The environment of with statements cannot contain any
lexical declaration so it doesn't need to be checked for
var/let hoisting conflicts.
For each element name of varNames , do
If
! thisEnv .HasBinding(name )
is true , then
Throw a SyntaxError
exception.
NOTE: Annex B.3.4
defines alternate semantics for the above
step.
NOTE: A direct
eval will not hoist var
declaration over a like-named lexical declaration.
Set thisEnv to thisEnv .[[OuterEnv]] .
Let privateIdentifiers be a new empty List .
Let pointer be privateEnv .
Repeat, while pointer is not null ,
For each Private Name
binding of pointer .[[Names]] ,
do
If privateIdentifiers does not contain
binding .[[Description]] , append
binding .[[Description]] to
privateIdentifiers .
Set pointer to pointer .[[OuterPrivateEnvironment]] .
If AllPrivateIdentifiersValid
of body with argument privateIdentifiers is
false , throw a SyntaxError exception.
Let functionsToInitialize be a new empty List .
Let declaredFunctionNames be a new empty List .
For each element d of varDeclarations , in reverse List order, do
If d is not either a VariableDeclaration , a
ForBinding ,
or a BindingIdentifier , then
Assert : d is either
a FunctionDeclaration ,
a GeneratorDeclaration ,
an AsyncFunctionDeclaration ,
or an AsyncGeneratorDeclaration .
NOTE: If there are multiple function declarations for the same name,
the last declaration is used.
Let fn be the sole element of the BoundNames
of d .
If declaredFunctionNames does not contain fn ,
then
If varEnv is a Global
Environment Record , then
Let fnDefinable be ? CanDeclareGlobalFunction (varEnv ,
fn ).
If fnDefinable is
false , throw a
TypeError exception.
Append fn to declaredFunctionNames .
Insert d as the first element of
functionsToInitialize .
Let declaredVarNames be a new empty List .
For each element d of varDeclarations , do
If d is either a VariableDeclaration , a
ForBinding ,
or a BindingIdentifier , then
For each String vn of the BoundNames
of d , do
If declaredFunctionNames does not contain
vn , then
If varEnv is a Global
Environment Record , then
Let vnDefinable be
? CanDeclareGlobalVar (varEnv ,
vn ).
If vnDefinable is
false , throw a
TypeError exception.
If declaredVarNames does not contain
vn , then
Append vn to
declaredVarNames .
NOTE: Annex
B.3.2.3
adds additional steps at this point.
NOTE: No abnormal
terminations occur after this algorithm step unless varEnv is a Global Environment
Record and the global object is a
Proxy exotic object .
Let lexDeclarations be the LexicallyScopedDeclarations
of body .
For each element d of lexDeclarations , do
NOTE: Lexically declared names are only instantiated here but not
initialized.
For each element dn of the BoundNames of
d , do
If IsConstantDeclaration
of d is true , then
Perform
? lexEnv .CreateImmutableBinding(dn ,
true ).
Else,
Perform
? lexEnv .CreateMutableBinding(dn ,
false ).
For each Parse Node f of
functionsToInitialize , do
Let fn be the sole element of the BoundNames of
f .
Let fo be InstantiateFunctionObject
of f with arguments lexEnv and privateEnv .
If varEnv is a Global
Environment Record , then
Perform ? CreateGlobalFunctionBinding (varEnv ,
fn , fo , true ).
Else,
Let bindingExists be
! varEnv .HasBinding(fn ).
If bindingExists is false , then
NOTE: The following invocation cannot return an abrupt
completion because of the validation
preceding step 14 .
Perform
! varEnv .CreateMutableBinding(fn ,
true ).
Perform
! varEnv .InitializeBinding(fn ,
fo ).
Else,
Perform
! varEnv .SetMutableBinding(fn ,
fo , false ).
For each String vn of declaredVarNames , do
If varEnv is a Global
Environment Record , then
Perform ? CreateGlobalVarBinding (varEnv ,
vn , true ).
Else,
Let bindingExists be
! varEnv .HasBinding(vn ).
If bindingExists is false , then
NOTE: The following invocation cannot return an abrupt
completion because of the validation
preceding step 14 .
Perform
! varEnv .CreateMutableBinding(vn ,
true ).
Perform
! varEnv .InitializeBinding(vn ,
undefined ).
Return unused .
Note
An alternative version of this algorithm is described in B.3.4 .
19.2.2 isFinite ( number )
This function is the %isFinite% intrinsic object.
It performs the following steps when called:
Let num be ? ToNumber (number ).
If num is not finite , return false .
Otherwise, return true .
19.2.3 isNaN ( number )
This function is the %isNaN% intrinsic object.
It performs the following steps when called:
Let num be ? ToNumber (number ).
If num is NaN , return true .
Otherwise, return false .
Note
A reliable way for ECMAScript code to test if a value X is
NaN is an expression of the form X !== X. The result
will be true if and only if X is NaN .
19.2.4 parseFloat ( string )
This function produces a Number value dictated by interpretation of the contents of the
string argument as a decimal literal.
It is the %parseFloat% intrinsic object.
It performs the following steps when called:
Let inputString be ? ToString (string ).
Let trimmedString be ! TrimString (inputString ,
start ).
Let trimmed be StringToCodePoints (trimmedString ).
Let trimmedPrefix be the longest prefix of trimmed that satisfies
the syntax of a StrDecimalLiteral , which might be
trimmed itself. If there is no such prefix, return NaN .
Let parsedNumber be ParseText (trimmedPrefix , StrDecimalLiteral ).
Assert :
parsedNumber is a Parse Node .
Return the StringNumericValue
of parsedNumber .
Note
This function may interpret only a leading portion of string as a Number
value; it ignores any code units that cannot be interpreted as part of the notation of a
decimal literal, and no indication is given that any such code units were ignored.
19.2.5 parseInt ( string , radix )
This function produces an integral Number dictated by interpretation of the
contents of string according to the specified radix . Leading white space
in string is ignored. If radix coerces to 0 (such as when it is
undefined ), it is assumed to be 10 except when the number representation
begins with "0x" or "0X" , in which case it is assumed to
be 16. If radix is 16, the number representation may optionally begin with
"0x" or "0X" .
It is the %parseInt% intrinsic object.
It performs the following steps when called:
Let inputString be ? ToString (string ).
Let S be ! TrimString (inputString ,
start ).
Let sign be 1.
If S is not empty and the first code unit of S is the code unit
0x002D (HYPHEN-MINUS), set sign to -1.
If S is not empty and the first code unit of S is either the code
unit 0x002B (PLUS SIGN) or the code unit 0x002D (HYPHEN-MINUS), set S to the
substring
of S from index 1.
Let R be ℝ (?
ToInt32 (radix )).
Let stripPrefix be true .
If R ≠ 0, then
If R < 2 or R > 36, return NaN .
If R ≠ 16, set stripPrefix to false .
Else,
Set R to 10.
If stripPrefix is true , then
If the length of S is at least 2 and the first two code units of
S are either "0x" or "0X" , then
Set S to the substring of S from
index 2.
Set R to 16.
If S contains a code unit that is not a radix-R digit, let
end be the index within S of the first such code unit; otherwise
let end be the length of S .
Let Z be the substring of S from 0 to
end .
If Z is empty, return NaN .
Let mathInt be the integer value that is represented by Z
in radix-R notation, using the letters A through Z and a
through z for digits with values 10 through 35. (However, if R = 10
and Z contains more than 20 significant digits, every significant digit after
the 20th may be replaced by a 0 digit, at the option of the implementation; and if
R is not one of 2, 4, 8, 10, 16, or 32, then mathInt may be an
implementation-approximated
integer
representing the integer value denoted by Z in
radix-R notation.)
If mathInt = 0, then
If sign = -1, return -0 𝔽 .
Return +0 𝔽 .
Return 𝔽 (sign × mathInt ).
Note
This function may interpret only a leading portion of string as an integer value; it
ignores any code units that cannot be interpreted as part of the notation of an
integer , and
no indication is given that any such code units were ignored.
19.2.6 URI Handling Functions
Uniform Resource Identifiers, or URIs, are Strings that identify resources (e.g. web pages or
files) and transport protocols by which to access them (e.g. HTTP or FTP) on the Internet. The
ECMAScript language itself does not provide any support for using URIs except for functions that
encode and decode URIs as described in this section. encodeURI and
decodeURI are intended to work with complete URIs; they assume that any reserved
characters are intended to have special meaning (e.g., as delimiters) and so are not encoded.
encodeURIComponent and decodeURIComponent are intended to work with
the individual components of a URI; they assume that any reserved characters represent text and
must be encoded to avoid special meaning when the component is part of a complete URI.
Note 1
The set of reserved characters is based upon RFC 2396 and does not reflect changes
introduced by the more recent RFC 3986.
Note 2
Many implementations of ECMAScript provide additional functions and methods that
manipulate web pages; these functions are beyond the scope of this standard.
19.2.6.1 decodeURI ( encodedURI )
This function computes a new version of a URI in which each escape sequence and UTF-8
encoding of the sort that might be introduced by the encodeURI function is
replaced with the UTF-16 encoding of the code point that it represents. Escape sequences
that could not have been introduced by encodeURI are not replaced.
It is the %decodeURI% intrinsic object.
It performs the following steps when called:
Let uriString be ? ToString (encodedURI ).
Let preserveEscapeSet be ";/?:@&=+$,#" .
Return ? Decode (uriString ,
preserveEscapeSet ).
19.2.6.2 decodeURIComponent ( encodedURIComponent )
This function computes a new version of a URI in which each escape sequence and UTF-8
encoding of the sort that might be introduced by the encodeURIComponent
function is replaced with the UTF-16 encoding of the code point that it represents.
It is the %decodeURIComponent% intrinsic object.
It performs the following steps when called:
Let componentString be ? ToString (encodedURIComponent ).
Let preserveEscapeSet be the empty String.
Return ? Decode (componentString ,
preserveEscapeSet ).
19.2.6.3 encodeURI ( uri )
This function computes a new version of a UTF-16 encoded (6.1.4 ) URI in which
each instance of certain code points is replaced by one, two, three, or four escape
sequences representing the UTF-8 encoding of the code point.
It is the %encodeURI% intrinsic object.
It performs the following steps when called:
Let uriString be ? ToString (uri ).
Let extraUnescaped be ";/?:@&=+$,#" .
Return ? Encode (uriString ,
extraUnescaped ).
19.2.6.4 encodeURIComponent ( uriComponent )
This function computes a new version of a UTF-16 encoded (6.1.4 ) URI in which
each instance of certain code points is replaced by one, two, three, or four escape
sequences representing the UTF-8 encoding of the code point.
It is the %encodeURIComponent% intrinsic object.
It performs the following steps when called:
Let componentString be ? ToString (uriComponent ).
Let extraUnescaped be the empty String.
Return ? Encode (componentString ,
extraUnescaped ).
19.2.6.5 Encode ( string , extraUnescaped )
The abstract operation Encode takes arguments string (a String) and
extraUnescaped (a String) and returns either a normal completion
containing a String or a throw completion . It
performs URI encoding and escaping, interpreting string as a sequence of UTF-16
encoded code points as described in 6.1.4 . If a
character is identified as unreserved in RFC 2396 or appears in extraUnescaped ,
it is not escaped. It performs the following steps when called:
Let len be the length of string .
Let R be the empty String.
Let alwaysUnescaped be the string-concatenation of
the ASCII word characters and
"-.!~*'()" .
Let unescapedSet be the string-concatenation of
alwaysUnescaped and extraUnescaped .
Let k be 0.
Repeat, while k < len ,
Let C be the code unit at index k within
string .
If unescapedSet contains C , then
Set k to k + 1.
Set R to the string-concatenation
of R and C .
Else,
Let cp be CodePointAt (string ,
k ).
If cp .[[IsUnpairedSurrogate]] is
true , throw a URIError
exception.
Set k to k + cp .[[CodeUnitCount]] .
Let Octets be the List
of octets resulting by applying the UTF-8 transformation to
cp .[[CodePoint]] .
For each element octet of Octets , do
Let hex be the String representation of
octet , formatted as an uppercase hexadecimal
number.
Set R to the string-concatenation
of R , "%" , and StringPad (hex ,
2, "0" , start ).
Return R .
Note
Because percent-encoding is used to represent individual octets, a single code point
may be expressed as multiple consecutive escape sequences (one for each of its 8-bit
UTF-8 code units).
19.2.6.6 Decode ( string ,
preserveEscapeSet )
The abstract operation Decode takes arguments string (a String) and
preserveEscapeSet (a String) and returns either a normal completion
containing a String or a throw completion . It
performs URI unescaping and decoding, preserving any escape sequences that correspond to
Basic Latin characters in preserveEscapeSet . It performs the following steps when
called:
Let len be the length of string .
Let R be the empty String.
Let k be 0.
Repeat, while k < len ,
Let C be the code unit at index k within
string .
Let S be C .
If C is the code unit 0x0025 (PERCENT SIGN), then
If k + 3 > len , throw a
URIError exception.
Let escape be the substring of
string from k to k + 3.
Let B be ParseHexOctet (string ,
k + 1).
If B is not an integer , throw
a URIError exception.
Set k to k + 2.
Let n be the number of leading 1 bits in B .
If n = 0, then
Let asciiChar be the code unit whose numeric
value is B .
If preserveEscapeSet contains
asciiChar , set S to escape ;
otherwise set S to asciiChar .
Else,
If n = 1 or n > 4, throw a
URIError exception.
Let Octets be « B ».
Let j be 1.
Repeat, while j < n ,
Set k to k + 1.
If k + 3 > len , throw a
URIError exception.
If the code unit at index k within
string is not the code unit 0x0025
(PERCENT SIGN), throw a URIError
exception.
Let continuationByte be ParseHexOctet (string ,
k + 1).
If continuationByte is not an integer ,
throw a URIError exception.
Append continuationByte to
Octets .
Set k to k + 2.
Set j to j + 1.
Assert : The length of
Octets is n .
If Octets does not contain a valid UTF-8 encoding
of a Unicode code point, throw a URIError
exception.
Let V be the code point obtained by applying the
UTF-8 transformation to Octets , that is, from a
List
of octets into a 21-bit value.
Set S to UTF16EncodeCodePoint (V ).
Set R to the string-concatenation of
R and S .
Set k to k + 1.
Return R .
Note
RFC 3629 prohibits the decoding of invalid UTF-8 octet sequences. For example, the
invalid sequence 0xC0 0x80 must not decode into the code unit 0x0000.
Implementations of the Decode algorithm are required to throw a
URIError when encountering such invalid sequences.
19.2.6.7 ParseHexOctet ( string , position
)
The abstract operation ParseHexOctet takes arguments string (a String) and
position (a non-negative integer ) and returns either a non-negative integer or a non-empty
List of
SyntaxError objects. It parses a sequence of two hexadecimal characters
at the specified position in string into an unsigned 8-bit integer . It performs
the following steps when called:
Let len be the length of string .
Assert :
position + 2 ≤ len .
Let hexDigits be the substring of string from
position to position + 2.
Let parseResult be ParseText (hexDigits , HexDigits [~Sep] ).
If parseResult is not a Parse Node ,
return parseResult .
Let n be the MV of parseResult .
Assert :
n is in the inclusive interval from 0 to 255.
Return n .
19.3 Constructor Properties of the Global Object
19.3.1 AggregateError ( . . . )
See 20.5.7.1 .
19.3.2 Array ( . . . )
See 23.1.1 .
19.3.3 ArrayBuffer ( . . . )
See 25.1.4 .
19.3.4 BigInt ( . . . )
See 21.2.1 .
19.3.5 BigInt64Array ( . . . )
See 23.2.5 .
19.3.6 BigUint64Array ( . . . )
See 23.2.5 .
19.3.7 Boolean ( . . . )
See 20.3.1 .
19.3.8 DataView ( . . . )
See 25.3.2 .
19.3.9 Date ( . . . )
See 21.4.2 .
19.3.10 Error ( . . . )
See 20.5.1 .
19.3.11 EvalError ( . . . )
See 20.5.5.1 .
19.3.12 FinalizationRegistry ( . . . )
See 26.2.1 .
19.3.13 Float16Array ( . . . )
See 23.2.5 .
19.3.14 Float32Array ( . . . )
See 23.2.5 .
19.3.15 Float64Array ( . . . )
See 23.2.5 .
19.3.16 Function ( . . . )
See 20.2.1 .
19.3.17 Int8Array ( . . . )
See 23.2.5 .
19.3.18 Int16Array ( . . . )
See 23.2.5 .
19.3.19 Int32Array ( . . . )
See 23.2.5 .
19.3.20 Iterator ( . . . )
See 27.1.3.1 .
19.3.21 Map ( . . . )
See 24.1.1 .
19.3.22 Number ( . . . )
See 21.1.1 .
19.3.23 Object ( . . . )
See 20.1.1 .
19.3.24 Promise ( . . . )
See 27.2.3 .
19.3.25 Proxy ( . . . )
See 28.2.1 .
19.3.26 RangeError ( . . . )
See 20.5.5.2 .
19.3.27 ReferenceError ( . . . )
See 20.5.5.3 .
19.3.28 RegExp ( . . . )
See 22.2.4 .
19.3.29 Set ( . . . )
See 24.2.2 .
19.3.30 SharedArrayBuffer ( . . . )
See 25.2.3 .
19.3.31 String ( . . . )
See 22.1.1 .
19.3.32 Symbol ( . . . )
See 20.4.1 .
19.3.33 SyntaxError ( . . . )
See 20.5.5.4 .
19.3.34 TypeError ( . . . )
See 20.5.5.5 .
19.3.35 Uint8Array ( . . . )
See 23.2.5 .
19.3.36 Uint8ClampedArray ( . . . )
See 23.2.5 .
19.3.37 Uint16Array ( . . . )
See 23.2.5 .
19.3.38 Uint32Array ( . . . )
See 23.2.5 .
19.3.39 URIError ( . . . )
See 20.5.5.6 .
19.3.40 WeakMap ( . . . )
See 24.3.1 .
19.3.41 WeakRef ( . . . )
See 26.1.1 .
19.3.42 WeakSet ( . . . )
See 24.4 .
19.4 Other Properties of the Global Object
19.4.1 Atomics
See 25.4 .
19.4.2 JSON
See 25.5 .
19.4.3 Math
See 21.3 .
19.4.4 Reflect
See 28.1 .
20 Fundamental Objects
20.1 Object Objects
20.1.1 The Object Constructor
The Object constructor :
is %Object% .
is the initial value of the "Object" property of the global
object .
creates a new ordinary object when called as a constructor .
performs a type conversion when called as a function rather than as a constructor .
may be used as the value of an extends clause of a class definition.
20.1.1.1 Object ( [ value ] )
This function performs the following steps when called:
If NewTarget is neither undefined nor the active function object , then
Return ? OrdinaryCreateFromConstructor (NewTarget,
"%Object.prototype%" ).
If value is either undefined or
null , return OrdinaryObjectCreate (%Object.prototype% ).
Return ! ToObject (value ).
20.1.2 Properties of the Object Constructor
The Object constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has a "length" property whose value is 1 𝔽 .
has the following additional properties:
20.1.2.1 Object.assign ( target ,
...sources )
This function copies the values of all of the enumerable own properties from one or more
source objects to a target object.
It performs the following steps when called:
Let to be ? ToObject (target ).
If only one argument was passed, return to .
For each element nextSource of sources , do
If nextSource is neither undefined nor
null , then
Let from be ! ToObject (nextSource ).
Let keys be ? from .[[OwnPropertyKeys]] () .
For each element nextKey of keys , do
Let desc be ? from .[[GetOwnProperty]] (nextKey ).
If desc is not undefined and
desc .[[Enumerable]] is
true , then
Let propValue be ? Get (from ,
nextKey ).
Perform ? Set (to ,
nextKey , propValue ,
true ).
Return to .
The "length" property of this function is
2 𝔽 .
20.1.2.2 Object.create ( O , Properties )
This function creates a new object with a specified prototype.
It performs the following steps when called:
If O is not an Object and O is
not null , throw a TypeError exception.
Let obj be OrdinaryObjectCreate (O ).
If Properties is not undefined , then
Return ? ObjectDefineProperties (obj ,
Properties ).
Return obj .
20.1.2.3 Object.defineProperties ( O ,
Properties )
This function adds own properties and/or updates the attributes of existing own properties of
an object.
It performs the following steps when called:
If O is not an Object , throw a
TypeError exception.
Return ? ObjectDefineProperties (O ,
Properties ).
20.1.2.3.1 ObjectDefineProperties ( O ,
Properties )
The abstract operation ObjectDefineProperties takes arguments O (an Object)
and Properties (an ECMAScript language
value ) and returns either a normal completion
containing an Object or a throw
completion . It performs the following steps when called:
Let props be ? ToObject (Properties ).
Let keys be ? props .[[OwnPropertyKeys]] () .
Let descriptors be a new empty List .
For each element nextKey of keys , do
Let propDesc be ? props .[[GetOwnProperty]] (nextKey ).
If propDesc is not undefined and
propDesc .[[Enumerable]] is
true , then
Let descObj be ? Get (props ,
nextKey ).
Let desc be ? ToPropertyDescriptor (descObj ).
Append the Record
{ [[Key]] : nextKey , [[Descriptor]] : desc }
to descriptors .
For each element property of descriptors , do
Perform ? DefinePropertyOrThrow (O ,
property .[[Key]] ,
property .[[Descriptor]] ).
Return O .
20.1.2.4 Object.defineProperty ( O , P ,
Attributes )
This function adds an own property and/or updates the attributes of an existing own property
of an object.
It performs the following steps when called:
If O is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (P ).
Let desc be ? ToPropertyDescriptor (Attributes ).
Perform ? DefinePropertyOrThrow (O ,
key , desc ).
Return O .
20.1.2.5 Object.entries ( O )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let entryList be ? EnumerableOwnProperties (obj ,
key+value ).
Return CreateArrayFromList (entryList ).
20.1.2.6 Object.freeze ( O )
This function performs the following steps when called:
If O is not an Object , return
O .
Let status be ? SetIntegrityLevel (O ,
frozen ).
If status is false , throw a
TypeError exception.
Return O .
20.1.2.7 Object.fromEntries ( iterable )
This function performs the following steps when called:
Perform ? RequireObjectCoercible (iterable ).
Let obj be OrdinaryObjectCreate (%Object.prototype% ).
Assert :
obj is an extensible ordinary object with no own
properties.
Let closure be a new Abstract Closure
with parameters (key , value ) that captures obj and
performs the following steps when called:
Let propertyKey be ? ToPropertyKey (key ).
Perform ! CreateDataPropertyOrThrow (obj ,
propertyKey , value ).
Return NormalCompletion (undefined ).
Let adder be CreateBuiltinFunction (closure ,
2, "" , « »).
Return ? AddEntriesFromIterable (obj ,
iterable , adder ).
Note
The function created for adder is never directly accessible to ECMAScript
code.
20.1.2.8 Object.getOwnPropertyDescriptor ( O ,
P )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let key be ? ToPropertyKey (P ).
Let desc be ? obj .[[GetOwnProperty]] (key ).
Return FromPropertyDescriptor (desc ).
20.1.2.9 Object.getOwnPropertyDescriptors ( O )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let ownKeys be ? obj .[[OwnPropertyKeys]] () .
Let descriptors be OrdinaryObjectCreate (%Object.prototype% ).
For each element key of ownKeys , do
Let desc be ? obj .[[GetOwnProperty]] (key ).
Let descriptor be FromPropertyDescriptor (desc ).
If descriptor is not undefined , perform
! CreateDataPropertyOrThrow (descriptors ,
key , descriptor ).
Return descriptors .
20.1.2.10 Object.getOwnPropertyNames ( O )
This function performs the following steps when called:
Return CreateArrayFromList (?
GetOwnPropertyKeys (O ,
string )).
20.1.2.11 Object.getOwnPropertySymbols ( O )
This function performs the following steps when called:
Return CreateArrayFromList (?
GetOwnPropertyKeys (O ,
symbol )).
20.1.2.11.1 GetOwnPropertyKeys ( O ,
type )
The abstract operation GetOwnPropertyKeys takes arguments O (an ECMAScript language value )
and type (string or symbol ) and
returns either a normal completion
containing a List of property
keys or a throw
completion . It performs the following steps when called:
Let obj be ? ToObject (O ).
Let keys be ? obj .[[OwnPropertyKeys]] () .
Let nameList be a new empty List .
For each element nextKey of keys , do
If nextKey is a
Symbol and type is
symbol , or if nextKey is a
String and type is
string , then
Append nextKey to nameList .
Return nameList .
20.1.2.12 Object.getPrototypeOf ( O )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Return ? obj .[[GetPrototypeOf]] () .
20.1.2.13 Object.groupBy ( items , callback
)
Note
callback should be a function that accepts two arguments.
groupBy calls callback once for each element in
items , in ascending order, and constructs a new object. Each value
returned by callback is coerced to a property key . For each
such property
key , the result object has a property whose key is that
property
key and whose value is an array containing all the elements
for which the callback return value coerced to that key.
callback is called with two arguments: the value of the element and the
index of the element.
The return value of groupBy is an object that does not inherit from
%Object.prototype% .
This function performs the following steps when called:
Let groups be ? GroupBy (items ,
callback , property ).
Let obj be OrdinaryObjectCreate (null ).
For each Record { [[Key]] , [[Elements]] }
g of groups , do
Let elements be CreateArrayFromList (g .[[Elements]] ).
Perform ! CreateDataPropertyOrThrow (obj ,
g .[[Key]] , elements ).
Return obj .
20.1.2.14 Object.hasOwn ( O , P )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let key be ? ToPropertyKey (P ).
Return ? HasOwnProperty (obj ,
key ).
20.1.2.15 Object.is ( value1 , value2 )
This function performs the following steps when called:
Return SameValue (value1 ,
value2 ).
20.1.2.16 Object.isExtensible ( O )
This function performs the following steps when called:
If O is not an Object , return
false .
Return ? IsExtensible (O ).
20.1.2.17 Object.isFrozen ( O )
This function performs the following steps when called:
If O is not an Object , return
true .
Return ? TestIntegrityLevel (O ,
frozen ).
20.1.2.18 Object.isSealed ( O )
This function performs the following steps when called:
If O is not an Object , return
true .
Return ? TestIntegrityLevel (O ,
sealed ).
20.1.2.19 Object.keys ( O )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let keyList be ? EnumerableOwnProperties (obj ,
key ).
Return CreateArrayFromList (keyList ).
20.1.2.20 Object.preventExtensions ( O )
This function performs the following steps when called:
If O is not an Object , return
O .
Let status be ? O .[[PreventExtensions]] () .
If status is false , throw a
TypeError exception.
Return O .
20.1.2.21 Object.prototype
The initial value of Object.prototype is the Object prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.1.2.22 Object.seal ( O )
This function performs the following steps when called:
If O is not an Object , return
O .
Let status be ? SetIntegrityLevel (O ,
sealed ).
If status is false , throw a
TypeError exception.
Return O .
20.1.2.23 Object.setPrototypeOf ( O , proto
)
This function performs the following steps when called:
Set O to ? RequireObjectCoercible (O ).
If proto is not an Object and proto
is not null , throw a TypeError exception.
If O is not an Object , return
O .
Let status be ? O .[[SetPrototypeOf]] (proto ).
If status is false , throw a
TypeError exception.
Return O .
20.1.2.24 Object.values ( O )
This function performs the following steps when called:
Let obj be ? ToObject (O ).
Let valueList be ? EnumerableOwnProperties (obj ,
value ).
Return CreateArrayFromList (valueList ).
20.1.3 Properties of the Object Prototype Object
The Object prototype object :
is %Object.prototype% .
has an [[Extensible]] internal slot whose value is
true .
has the internal methods defined for ordinary objects , except for the [[SetPrototypeOf]] method, which is as defined in 10.4.7.1 .
(Thus, it is an immutable prototype exotic
object .)
has a [[Prototype]] internal slot whose value is
null .
20.1.3.1 Object.prototype.constructor
The initial value of Object.prototype.constructor is %Object% .
20.1.3.2 Object.prototype.hasOwnProperty ( V )
This method performs the following steps when called:
Let P be ? ToPropertyKey (V ).
Let O be ? ToObject (this value).
Return ? HasOwnProperty (O ,
P ).
Note
The ordering of steps 1 and
2 is chosen to ensure
that any exception that would have been thrown by step 1 in previous
editions of this specification will continue to be thrown even if the
this value is undefined or
null .
20.1.3.3 Object.prototype.isPrototypeOf ( V )
This method performs the following steps when called:
If V is not an
Object , return false .
Let O be ? ToObject (this value).
Repeat,
Set V to ? V .[[GetPrototypeOf]] () .
If V is null , return false .
If SameValue (O ,
V ) is true , return true .
Note
The ordering of steps 1 and
2 preserves the behaviour
specified by previous editions of this specification for the case where V
is not an object and the this value is
undefined or null .
20.1.3.4 Object.prototype.propertyIsEnumerable ( V )
This method performs the following steps when called:
Let P be ? ToPropertyKey (V ).
Let O be ? ToObject (this value).
Let desc be ? O .[[GetOwnProperty]] (P ).
If desc is undefined , return false .
Return desc .[[Enumerable]] .
Note 1
This method does not consider objects in the prototype chain.
Note 2
The ordering of steps 1 and
2 is chosen to
ensure that any exception that would have been thrown by step 1 in previous
editions of this specification will continue to be thrown even if the
this value is undefined or
null .
20.1.3.5 Object.prototype.toLocaleString ( [
reserved1 [ , reserved2 ] ] )
This method performs the following steps when called:
Let O be the this value.
Return ? Invoke (O ,
"toString" ).
The optional parameters to this method are not used but are intended to correspond to the
parameter pattern used by ECMA-402 toLocaleString methods. Implementations that
do not include ECMA-402 support must not use those parameter positions for other purposes.
Note 1
This method provides a generic toLocaleString implementation for objects
that have no locale-sensitive toString behaviour. Array,
Number, Date, and %TypedArray%
provide their own locale-sensitive toLocaleString methods.
Note 2
ECMA-402 intentionally does not provide an alternative to this default
implementation.
20.1.3.6 Object.prototype.toString ( )
This method performs the following steps when called:
If the this value is undefined , return
"[object Undefined]" .
If the this value is null , return
"[object Null]" .
Let O be ! ToObject (this value).
Let isArray be ? IsArray (O ).
If isArray is true , let builtinTag be
"Array" .
Else if O has a [[ParameterMap]] internal slot,
let builtinTag be "Arguments" .
Else if O has a [[Call]] internal method, let
builtinTag be "Function" .
Else if O has an [[ErrorData]] internal slot,
let builtinTag be "Error" .
Else if O has a [[BooleanData]] internal slot,
let builtinTag be "Boolean" .
Else if O has a [[NumberData]] internal slot,
let builtinTag be "Number" .
Else if O has a [[StringData]] internal slot,
let builtinTag be "String" .
Else if O has a [[DateValue]] internal slot, let
builtinTag be "Date" .
Else if O has a [[RegExpMatcher]] internal slot,
let builtinTag be "RegExp" .
Else, let builtinTag be "Object" .
Let tag be ? Get (O ,
%Symbol.toStringTag% ).
If tag is not a
String , set tag to builtinTag .
Return the string-concatenation of
"[object " , tag , and "]" .
Note
Historically, this method was occasionally used to access the String value of the
[[Class]] internal slot that was used in previous editions
of this specification as a nominal type tag for various built-in objects. The above
definition of toString preserves compatibility for legacy code that
uses toString as a test for those specific kinds of built-in objects.
It does not provide a reliable type testing mechanism for other kinds of built-in or
program defined objects. In addition, programs can use %Symbol.toStringTag% in ways
that will invalidate the reliability of such legacy type tests.
20.1.3.7 Object.prototype.valueOf ( )
This method performs the following steps when called:
Return ? ToObject (this value).
20.1.3.8 Object.prototype.__proto__
Object.prototype.__proto__ is an accessor property with
attributes { [[Enumerable]] : false , [[Configurable]] : true }. The [[Get]] and [[Set]] attributes are defined
as follows:
20.1.3.8.1 get Object.prototype.__proto__
The value of the [[Get]] attribute is a built-in function that
requires no arguments. It performs the following steps when called:
Let O be ? ToObject (this
value).
Return ? O .[[GetPrototypeOf]] () .
20.1.3.8.2 set Object.prototype.__proto__
The value of the [[Set]] attribute is a built-in function that
takes an argument proto . It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If proto is not an Object and
proto is not null , return
undefined .
If O is not an Object , return
undefined .
Let status be ? O .[[SetPrototypeOf]] (proto ).
If status is false , throw a
TypeError exception.
Return undefined .
20.1.3.9 Legacy Object.prototype Accessor Methods
20.1.3.9.1 Object.prototype.__defineGetter__ ( P ,
getter )
This method performs the following steps when called:
Let O be ? ToObject (this
value).
If IsCallable (getter ) is
false , throw a TypeError exception.
Let desc be PropertyDescriptor { [[Get]] :
getter , [[Enumerable]] :
true , [[Configurable]] :
true }.
Let key be ? ToPropertyKey (P ).
Perform ? DefinePropertyOrThrow (O ,
key , desc ).
Return undefined .
20.1.3.9.2 Object.prototype.__defineSetter__ ( P ,
setter )
This method performs the following steps when called:
Let O be ? ToObject (this
value).
If IsCallable (setter ) is
false , throw a TypeError exception.
Let desc be PropertyDescriptor { [[Set]] :
setter , [[Enumerable]] :
true , [[Configurable]] :
true }.
Let key be ? ToPropertyKey (P ).
Perform ? DefinePropertyOrThrow (O ,
key , desc ).
Return undefined .
20.1.3.9.3 Object.prototype.__lookupGetter__ ( P
)
This method performs the following steps when called:
Let O be ? ToObject (this
value).
Let key be ? ToPropertyKey (P ).
Repeat,
Let desc be ? O .[[GetOwnProperty]] (key ).
If desc is not undefined , then
If IsAccessorDescriptor (desc )
is true , return desc .[[Get]] .
Return undefined .
Set O to ? O .[[GetPrototypeOf]] () .
If O is null , return
undefined .
20.1.3.9.4 Object.prototype.__lookupSetter__ ( P
)
This method performs the following steps when called:
Let O be ? ToObject (this
value).
Let key be ? ToPropertyKey (P ).
Repeat,
Let desc be ? O .[[GetOwnProperty]] (key ).
If desc is not undefined , then
If IsAccessorDescriptor (desc )
is true , return desc .[[Set]] .
Return undefined .
Set O to ? O .[[GetPrototypeOf]] () .
If O is null , return
undefined .
20.1.4 Properties of Object Instances
Object instances have no special properties beyond those inherited from the Object prototype
object .
20.2 Function Objects
20.2.1 The Function Constructor
The Function constructor :
is %Function% .
is the initial value of the "Function" property of the global
object .
creates and initializes a new function object when called as a function
rather than as a constructor . Thus the function call
Function(…) is equivalent to the object creation expression
new Function(…) with the same arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Function behaviour must include a super call to the Function constructor to
create and initialize a subclass instance with the internal slots necessary for built-in
function behaviour. All ECMAScript syntactic forms for defining function
objects create instances of Function. There is no syntactic means to
create instances of Function subclasses except for the built-in GeneratorFunction,
AsyncFunction, and AsyncGeneratorFunction subclasses.
20.2.1.1 Function ( ...parameterArgs ,
bodyArg )
The last argument (if any) specifies the body (executable code) of a function; any preceding
arguments specify formal parameters.
This function performs the following steps when called:
Let C be the active function object .
If bodyArg is not present, set bodyArg to the empty String.
Return ? CreateDynamicFunction (C ,
NewTarget, normal , parameterArgs ,
bodyArg ).
Note
It is permissible but not necessary to have one argument for each formal parameter to
be specified. For example, all three of the following expressions produce the same
result:
new Function ("a" , "b" , "c" , "return a+b+c" )
new Function ("a, b, c" , "return a+b+c" )
new Function ("a,b" , "c" , "return a+b+c" )
20.2.1.1.1 CreateDynamicFunction ( constructor ,
newTarget , kind , parameterArgs , bodyArg )
The abstract operation CreateDynamicFunction takes arguments constructor (a
constructor ), newTarget (a
constructor or undefined ),
kind (normal , generator ,
async , or async-generator ),
parameterArgs (a List
of ECMAScript language
values ), and bodyArg (an ECMAScript language value )
and returns either a normal completion
containing an ECMAScript function object or a
throw
completion . constructor is the constructor
function that is performing this action. newTarget is the constructor
that new was initially applied to. parameterArgs and
bodyArg reflect the argument values that were passed to
constructor . It performs the following steps when called:
If newTarget is undefined , set
newTarget to constructor .
If kind is normal , then
Let prefix be "function" .
Let exprSym be the grammar symbol FunctionExpression .
Let bodySym be the grammar symbol FunctionBody [~Yield,
~Await] .
Let parameterSym be the grammar symbol FormalParameters [~Yield,
~Await] .
Let fallbackProto be
"%Function.prototype%" .
Else if kind is generator , then
Let prefix be "function*" .
Let exprSym be the grammar symbol GeneratorExpression .
Let bodySym be the grammar symbol GeneratorBody .
Let parameterSym be the grammar symbol FormalParameters [+Yield,
~Await] .
Let fallbackProto be
"%GeneratorFunction.prototype%" .
Else if kind is async , then
Let prefix be "async function" .
Let exprSym be the grammar symbol AsyncFunctionExpression .
Let bodySym be the grammar symbol AsyncFunctionBody .
Let parameterSym be the grammar symbol FormalParameters [~Yield,
+Await] .
Let fallbackProto be
"%AsyncFunction.prototype%" .
Else,
Assert : kind is
async-generator .
Let prefix be "async function*" .
Let exprSym be the grammar symbol AsyncGeneratorExpression .
Let bodySym be the grammar symbol AsyncGeneratorBody .
Let parameterSym be the grammar symbol FormalParameters [+Yield,
+Await] .
Let fallbackProto be
"%AsyncGeneratorFunction.prototype%" .
Let argCount be the number of elements in parameterArgs .
Let parameterStrings be a new empty List .
For each element arg of parameterArgs , do
Append ? ToString (arg ) to
parameterStrings .
Let bodyString be ? ToString (bodyArg ).
Let currentRealm be the current Realm Record .
Perform ? HostEnsureCanCompileStrings (currentRealm ,
parameterStrings , bodyString , false ).
Let P be the empty String.
If argCount > 0, then
Set P to parameterStrings [0].
Let k be 1.
Repeat, while k < argCount ,
Let nextArgString be
parameterStrings [k ].
Set P to the string-concatenation
of P , "," (a comma), and
nextArgString .
Set k to k + 1.
Let bodyParseString be the string-concatenation of
0x000A (LINE FEED), bodyString , and 0x000A (LINE FEED).
Let sourceString be the string-concatenation of
prefix , " anonymous(" , P , 0x000A (LINE
FEED), ") {" , bodyParseString , and
"}" .
Let sourceText be StringToCodePoints (sourceString ).
Let parameters be ParseText (P ,
parameterSym ).
If parameters is a List of
errors, throw a SyntaxError exception.
Let body be ParseText (bodyParseString ,
bodySym ).
If body is a List of
errors, throw a SyntaxError exception.
NOTE: The parameters and body are parsed separately to ensure that each is valid
alone. For example, new Function("/*", "*/ ) {") does not evaluate
to a function.
NOTE: If this step is reached, sourceText must have the syntax of
exprSym (although the reverse implication does not hold). The purpose
of the next two steps is to enforce any Early Error rules which apply to
exprSym directly.
Let expr be ParseText (sourceText ,
exprSym ).
If expr is a List of
errors, throw a SyntaxError exception.
Let proto be ? GetPrototypeFromConstructor (newTarget ,
fallbackProto ).
Let env be currentRealm .[[GlobalEnv]] .
Let privateEnv be null .
Let F be OrdinaryFunctionCreate (proto ,
sourceText , parameters , body ,
non-lexical-this , env , privateEnv ).
Perform SetFunctionName (F ,
"anonymous" ).
If kind is generator , then
Let prototype be OrdinaryObjectCreate (%GeneratorPrototype% ).
Perform ! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] : prototype , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] :
false }).
Else if kind is async-generator , then
Let prototype be OrdinaryObjectCreate (%AsyncGeneratorPrototype% ).
Perform ! DefinePropertyOrThrow (F ,
"prototype" , PropertyDescriptor { [[Value]] : prototype , [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] :
false }).
Else if kind is normal , then
Perform MakeConstructor (F ).
NOTE: Functions whose kind is async are not
constructable and do not have a [[Construct]] internal
method or a "prototype" property.
Return F .
Note
CreateDynamicFunction defines a "prototype" property on any
function it creates whose kind is not async to
provide for the possibility that the function will be used as a constructor .
20.2.2 Properties of the Function Constructor
The Function constructor :
is itself a built-in function object .
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has a
"length" property whose value is 1 𝔽 .
has the following properties:
20.2.2.1 Function.prototype
The value of Function.prototype is the Function prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.2.3 Properties of the Function Prototype Object
The Function prototype object :
is %Function.prototype% .
is itself a built-in function object .
accepts any arguments and returns undefined when invoked.
does not have a [[Construct]] internal method; it cannot be used as
a constructor with the new operator.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
does not have a "prototype" property.
has a "length" property whose value is
+0 𝔽 .
has a "name" property whose value is the empty String.
Note
The Function prototype object is specified to be a function object to ensure
compatibility with ECMAScript code that was created prior to the ECMAScript 2015
specification.
20.2.3.1 Function.prototype.apply ( thisArg ,
argArray )
This method performs the following steps when called:
Let func be the this value.
If IsCallable (func ) is
false , throw a TypeError exception.
If argArray is either undefined or
null , then
Perform PrepareForTailCall ().
Return ? Call (func ,
thisArg ).
Let argList be ? CreateListFromArrayLike (argArray ).
Perform PrepareForTailCall ().
Return ? Call (func , thisArg ,
argList ).
Note 1
The thisArg value is passed without modification as the
this value. This is a change from Edition 3, where an
undefined or null thisArg is
replaced with the global object and ToObject
is applied to all other values and that result is passed as the
this value. Even though the thisArg is passed without
modification, non-strict functions still
perform these transformations upon entry to the function.
Note 2
If func is either an arrow function or a bound function exotic
object , then the thisArg will be ignored by the
function [[Call]] in step 6 .
20.2.3.2 Function.prototype.bind ( thisArg ,
...args )
This method performs the following steps when called:
Let Target be the this value.
If IsCallable (Target ) is
false , throw a TypeError exception.
Let F be ? BoundFunctionCreate (Target ,
thisArg , args ).
Let L be 0.
Let targetHasLength be ? HasOwnProperty (Target ,
"length" ).
If targetHasLength is true , then
Let targetLen be ? Get (Target ,
"length" ).
If targetLen is a
Number , then
If targetLen is +∞ 𝔽 , then
Set L to +∞.
Else if targetLen is -∞ 𝔽 ,
then
Set L to 0.
Else,
Let targetLenAsInt be ! ToIntegerOrInfinity (targetLen ).
Assert :
targetLenAsInt is finite .
Let argCount be the number of elements in
args .
Set L to max (targetLenAsInt
- argCount , 0).
Perform SetFunctionLength (F ,
L ).
Let targetName be ? Get (Target ,
"name" ).
If targetName is not a
String , set targetName to the empty String.
Perform SetFunctionName (F ,
targetName , "bound" ).
Return F .
Note 1
Function
objects created using Function.prototype.bind
are exotic
objects . They also do not have a
"prototype" property.
Note 2
If Target is either an arrow function or a bound function exotic
object , then the thisArg passed to this method
will not be used by subsequent calls to F .
20.2.3.3 Function.prototype.call ( thisArg ,
...args )
This method performs the following steps when called:
Let func be the this value.
If IsCallable (func ) is
false , throw a TypeError exception.
Perform PrepareForTailCall ().
Return ? Call (func , thisArg ,
args ).
Note 1
The thisArg value is passed without modification as the
this value. This is a change from Edition 3, where an
undefined or null thisArg is
replaced with the global object and ToObject
is applied to all other values and that result is passed as the
this value. Even though the thisArg is passed without
modification, non-strict functions still
perform these transformations upon entry to the function.
Note 2
If func is either an arrow function or a bound function exotic
object , then the thisArg will be ignored by the
function [[Call]] in step 4 .
20.2.3.4 Function.prototype.constructor
The initial value of Function.prototype.constructor is %Function% .
20.2.3.5 Function.prototype.toString ( )
This method performs the following steps when called:
Let func be the this value.
If func is an Object , func has a
[[SourceText]] internal slot, func .[[SourceText]] is a sequence of Unicode code points, and
HostHasSourceTextAvailable (func )
is true , then
Return CodePointsToString (func .[[SourceText]] ).
If func is a built-in function
object , return an implementation-defined String
source code representation of func . The representation must have the
syntax of a NativeFunction . Additionally, if
func has an [[InitialName]] internal slot and
func .[[InitialName]] is a
String , the portion of the returned String that would be
matched by NativeFunctionAccessor opt
PropertyName must
be func .[[InitialName]] .
If func is an Object and IsCallable (func ) is
true , return an implementation-defined String
source code representation of func . The representation must have the
syntax of a NativeFunction .
Throw a TypeError exception.
NativeFunction :
function
NativeFunctionAccessor opt
PropertyName [~Yield,
~Await] opt
(
FormalParameters [~Yield,
~Await]
)
{
[
native
code
]
}
NativeFunctionAccessor
:
get
set
20.2.3.6 Function.prototype [ %Symbol.hasInstance% ] (
V )
This method performs the following steps when called:
Let F be the this value.
Return ? OrdinaryHasInstance (F ,
V ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
This is the default implementation of %Symbol.hasInstance% that most
functions inherit. %Symbol.hasInstance% is called by the
instanceof operator to determine whether a value is an instance of a
specific constructor . An expression such as
v instanceof F
evaluates as
F[%Symbol .hasInstance %](v)
A constructor function can control which
objects are recognized as its instances by instanceof by exposing a
different %Symbol.hasInstance% method on the function.
This property is non-writable and non-configurable to prevent tampering that could be used to
globally expose the target function of a bound function.
The value of the "name" property of this method is
"[Symbol.hasInstance]" .
20.2.4 Function Instances
Every Function instance is an ECMAScript function object and has the internal slots listed
in Table 30 .
Function
objects created using the Function.prototype.bind method
(20.2.3.2 ) have the internal slots
listed in Table
31 .
Function instances have the following properties:
20.2.4.1 length
The value of the "length" property is an integral Number that indicates
the typical number of arguments expected by the function. However, the language permits the
function to be invoked with some other number of arguments. The behaviour of a function when
invoked on a number of arguments other than the number specified by its
"length" property depends on the function. This property has the
attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }.
20.2.4.2 name
The value of the "name" property is a String that is
descriptive of the function. The name has no semantic significance but is typically a
variable or property
name that is used to refer to the function at its point of definition
in ECMAScript
source text . This property has the attributes { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : true }.
Anonymous functions objects that do not have a contextual name associated with them by this
specification use the empty String as the value of the "name" property.
20.2.4.3 prototype
Function instances that can be used as a constructor have a "prototype"
property. Whenever such a Function instance is created another ordinary
object is also created and is the initial value of the function's
"prototype" property. Unless otherwise specified, the value of the
"prototype" property is used to initialize the [[Prototype]] internal slot of the object created when that function
is invoked as a constructor .
This property has the attributes { [[Writable]] :
true , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
Function
objects created using Function.prototype.bind,
or by evaluating a MethodDefinition (that is not a
GeneratorMethod
or AsyncGeneratorMethod ) or an
ArrowFunction do
not have a "prototype" property.
20.2.5 HostHasSourceTextAvailable ( func )
The host-defined abstract operation
HostHasSourceTextAvailable takes argument func (a function object ) and returns a
Boolean. It allows host environments to prevent the source text
from being provided for func .
An implementation of HostHasSourceTextAvailable must conform to the following requirements:
It must be deterministic with respect to its parameters. Each time it is called with a
specific func as its argument, it must return the same result.
The default implementation of HostHasSourceTextAvailable is to return true .
20.3 Boolean Objects
20.3.1 The Boolean Constructor
The Boolean constructor :
is %Boolean% .
is the initial value of the "Boolean" property of the global
object .
creates and initializes a new Boolean object when called as a constructor .
performs a type conversion when called as a function rather than as a constructor .
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Boolean behaviour must include a super call to the Boolean constructor to
create and initialize the subclass instance with a [[BooleanData]]
internal slot.
20.3.1.1 Boolean ( value )
This function performs the following steps when called:
Let b be ToBoolean (value ).
If NewTarget is undefined , return b .
Let O be ? OrdinaryCreateFromConstructor (NewTarget,
"%Boolean.prototype%" , « [[BooleanData]] »).
Set O .[[BooleanData]] to b .
Return O .
20.3.2 Properties of the Boolean Constructor
The Boolean constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
20.3.2.1 Boolean.prototype
The initial value of Boolean.prototype is the Boolean prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.3.3 Properties of the Boolean Prototype Object
The Boolean prototype object :
is %Boolean.prototype% .
is an ordinary
object .
is itself a Boolean object; it has a [[BooleanData]] internal slot
with the value false .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
20.3.3.1 Boolean.prototype.constructor
The initial value of Boolean.prototype.constructor is %Boolean% .
20.3.3.2 Boolean.prototype.toString ( )
This method performs the following steps when called:
Let b be ? ThisBooleanValue (this
value).
If b is true , return "true" ; else
return "false" .
20.3.3.3 Boolean.prototype.valueOf ( )
This method performs the following steps when called:
Return ? ThisBooleanValue (this
value).
20.3.3.3.1 ThisBooleanValue ( value )
The abstract operation ThisBooleanValue takes argument value (an ECMAScript language value )
and returns either a normal completion
containing a Boolean or a throw
completion . It performs the following steps when called:
If value is a
Boolean , return value .
If value is an Object and value
has a [[BooleanData]] internal slot, then
Let b be value .[[BooleanData]] .
Assert : b is a
Boolean .
Return b .
Throw a TypeError exception.
20.3.4 Properties of Boolean Instances
Boolean instances are ordinary objects that inherit properties from the
Boolean prototype
object . Boolean instances have a [[BooleanData]]
internal slot. The [[BooleanData]] internal slot is the Boolean value
represented by this Boolean object.
20.4 Symbol Objects
20.4.1 The Symbol Constructor
The Symbol constructor :
is %Symbol% .
is the initial value of the "Symbol" property of the global
object .
returns a new Symbol value when called as a function.
is not intended to be used with the new operator.
is not intended to be subclassed.
may be used as the value of an extends clause of a class definition but a
super call to it will cause an exception.
20.4.1.1 Symbol ( [ description ] )
This function performs the following steps when called:
If NewTarget is not undefined , throw a
TypeError exception.
If description is undefined , let descString
be undefined .
Else, let descString be ? ToString (description ).
Return a new Symbol whose [[Description]] is
descString .
20.4.2 Properties of the Symbol Constructor
The Symbol constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
20.4.2.1 Symbol.asyncIterator
The initial value of Symbol.asyncIterator is the well-known symbol %Symbol.asyncIterator% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.2 Symbol.for ( key )
This function performs the following steps when called:
Let stringKey be ? ToString (key ).
For each element e of the GlobalSymbolRegistry
List , do
If e .[[Key]] is stringKey ,
return e .[[Symbol]] .
Assert : The
GlobalSymbolRegistry List does not
currently contain an entry for stringKey .
Let newSymbol be a new Symbol whose [[Description]] is stringKey .
Append the GlobalSymbolRegistry Record { [[Key]] : stringKey , [[Symbol]] : newSymbol } to the GlobalSymbolRegistry List .
Return newSymbol .
The GlobalSymbolRegistry List is an append-only List that is globally
available. It is shared by all realms . Prior to the evaluation of any ECMAScript code,
it is initialized as a new empty List .
Elements of the GlobalSymbolRegistry List are Records with the
structure defined in Table
63 .
Table 63: GlobalSymbolRegistry Record Fields
Field Name
Value
Usage
[[Key]]
a String
A string key used to globally identify a Symbol.
[[Symbol]]
a Symbol
A symbol that can be retrieved from any realm .
20.4.2.3 Symbol.hasInstance
The initial value of Symbol.hasInstance is the well-known symbol %Symbol.hasInstance% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.4 Symbol.isConcatSpreadable
The initial value of Symbol.isConcatSpreadable is the well-known symbol
%Symbol.isConcatSpreadable% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.5 Symbol.iterator
The initial value of Symbol.iterator is the well-known symbol %Symbol.iterator% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.6 Symbol.keyFor ( sym )
This function performs the following steps when called:
If sym is not a
Symbol , throw a TypeError exception.
Return KeyForSymbol (sym ).
20.4.2.7 Symbol.match
The initial value of Symbol.match is the well-known symbol %Symbol.match% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.8 Symbol.matchAll
The initial value of Symbol.matchAll is the well-known symbol %Symbol.matchAll% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.9 Symbol.prototype
The initial value of Symbol.prototype is the Symbol prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.10 Symbol.replace
The initial value of Symbol.replace is the well-known symbol %Symbol.replace% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.11 Symbol.search
The initial value of Symbol.search is the well-known symbol %Symbol.search% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.12 Symbol.species
The initial value of Symbol.species is the well-known symbol %Symbol.species% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.13 Symbol.split
The initial value of Symbol.split is the well-known symbol %Symbol.split% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.14 Symbol.toPrimitive
The initial value of Symbol.toPrimitive is the well-known symbol %Symbol.toPrimitive% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.15 Symbol.toStringTag
The initial value of Symbol.toStringTag is the well-known symbol %Symbol.toStringTag% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.2.16 Symbol.unscopables
The initial value of Symbol.unscopables is the well-known symbol %Symbol.unscopables% (Table
1 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.4.3 Properties of the Symbol Prototype Object
The Symbol prototype object :
20.4.3.1 Symbol.prototype.constructor
The initial value of Symbol.prototype.constructor is %Symbol% .
20.4.3.2 get Symbol.prototype.description
Symbol.prototype.description is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let s be the this value.
Let sym be ? ThisSymbolValue (s ).
Return sym .[[Description]] .
20.4.3.3 Symbol.prototype.toString ( )
This method performs the following steps when called:
Let sym be ? ThisSymbolValue (this
value).
Return SymbolDescriptiveString (sym ).
20.4.3.3.1 SymbolDescriptiveString ( sym )
The abstract operation SymbolDescriptiveString takes argument sym (a Symbol)
and returns a String. It performs the following steps when called:
Let desc be sym 's [[Description]]
value.
If desc is undefined , set desc to the
empty String.
Assert :
desc is a
String .
Return the string-concatenation of
"Symbol(" , desc , and ")" .
20.4.3.4 Symbol.prototype.valueOf ( )
This method performs the following steps when called:
Return ? ThisSymbolValue (this
value).
20.4.3.4.1 ThisSymbolValue ( value )
The abstract operation ThisSymbolValue takes argument value (an ECMAScript language value )
and returns either a normal completion
containing a Symbol or a throw
completion . It performs the following steps when called:
If value is a
Symbol , return value .
If value is an Object and value
has a [[SymbolData]] internal slot, then
Let s be value .[[SymbolData]] .
Assert : s is a
Symbol .
Return s .
Throw a TypeError exception.
20.4.3.5 Symbol.prototype [ %Symbol.toPrimitive% ] (
hint )
This method is called by ECMAScript language operators to convert a Symbol object to a
primitive value.
It performs the following steps when called:
Return ? ThisSymbolValue (this
value).
Note
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
The value of the "name" property of this method is
"[Symbol.toPrimitive]" .
20.4.3.6 Symbol.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Symbol" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
20.4.4 Properties of Symbol Instances
Symbol instances are ordinary objects that inherit properties from the
Symbol prototype
object . Symbol instances have a [[SymbolData]]
internal slot. The [[SymbolData]] internal slot is the Symbol value
represented by this Symbol object.
20.4.5 Abstract Operations for Symbols
20.4.5.1 KeyForSymbol ( sym )
The abstract operation KeyForSymbol takes argument sym (a Symbol) and returns a
String or undefined . If sym is in the GlobalSymbolRegistry
List , the String used to register sym will be returned. It
performs the following steps when called:
For each element e of the GlobalSymbolRegistry
List , do
If SameValue (e .[[Symbol]] , sym ) is
true , return e .[[Key]] .
Assert : The
GlobalSymbolRegistry List does not
currently contain an entry for sym .
Return undefined .
20.5 Error Objects
Instances of Error objects are thrown as exceptions when runtime errors occur. The Error objects may
also serve as base objects for user-defined exception classes.
When an ECMAScript implementation detects a runtime error, it throws a new instance of one of the
NativeError objects defined in 20.5.5 or a new instance
of the AggregateError object defined in 20.5.7 .
20.5.1 The Error Constructor
The Error constructor :
is %Error% .
is the initial value of the "Error" property of the global
object .
creates and initializes a new Error object when called as a function rather than as a
constructor . Thus the function call
Error(…) is equivalent to the object creation expression
new Error(…) with the same arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Error behaviour must include a super call to the Error constructor to
create and initialize subclass instances with an [[ErrorData]]
internal slot.
20.5.1.1 Error ( message [ , options ] )
This function performs the following steps when called:
If NewTarget is undefined , let newTarget be the
active function object ; else
let newTarget be NewTarget.
Let O be ? OrdinaryCreateFromConstructor (newTarget ,
"%Error.prototype%" , « [[ErrorData]] »).
If message is not undefined , then
Let msg be ? ToString (message ).
Perform CreateNonEnumerableDataPropertyOrThrow (O ,
"message" , msg ).
Perform ? InstallErrorCause (O ,
options ).
Return O .
20.5.2 Properties of the Error Constructor
The Error constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
20.5.2.1 Error.isError ( arg )
This function performs the following steps when called:
If arg is not an Object , return
false .
If arg does not have an [[ErrorData]] internal
slot, return false .
Return true .
20.5.2.2 Error.prototype
The initial value of Error.prototype is the Error prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
20.5.3 Properties of the Error Prototype Object
The Error prototype object :
is %Error.prototype% .
is an ordinary
object .
is not an Error instance and does not have an [[ErrorData]]
internal slot.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
20.5.3.1 Error.prototype.constructor
The initial value of Error.prototype.constructor is %Error% .
20.5.3.2 Error.prototype.message
The initial value of Error.prototype.message is the empty String.
20.5.3.3 Error.prototype.name
The initial value of Error.prototype.name is "Error" .
20.5.3.4 Error.prototype.toString ( )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let name be ? Get (O ,
"name" ).
If name is undefined , set name to
"Error" ; otherwise set name to ? ToString (name ).
Let msg be ? Get (O ,
"message" ).
If msg is undefined , set msg to the empty
String; otherwise set msg to ? ToString (msg ).
If name is the empty String, return msg .
If msg is the empty String, return name .
Return the string-concatenation of
name , the code unit 0x003A (COLON), the code unit 0x0020 (SPACE), and
msg .
20.5.4 Properties of Error Instances
Error instances are ordinary objects that inherit properties from the
Error prototype
object and have an [[ErrorData]] internal slot
whose value is undefined . The only specified use of [[ErrorData]] is to identify Error, AggregateError, and
NativeError instances as Error objects within Object.prototype.toString
and Error.isError.
20.5.5 Native Error Types Used in This Standard
A new instance of one of the NativeError objects below or of the AggregateError object
is thrown when a runtime error is detected. All NativeError objects share the same
structure, as described in 20.5.6 .
20.5.5.1 EvalError
The EvalError constructor is %EvalError% .
This exception is not currently used within this specification. This object remains for
compatibility with previous editions of this specification.
20.5.5.2 RangeError
The RangeError constructor is %RangeError% .
Indicates a value that is not in the set or range of allowable values.
20.5.5.3 ReferenceError
The ReferenceError constructor is %ReferenceError% .
Indicate that an invalid reference has been detected.
20.5.5.4 SyntaxError
The SyntaxError constructor is %SyntaxError% .
Indicates that a parsing error has occurred.
20.5.5.5 TypeError
The TypeError constructor is %TypeError% .
TypeError is used to indicate an unsuccessful operation when none of the other
NativeError objects are an appropriate indication of the failure cause.
20.5.5.6 URIError
The URIError constructor is %URIError% .
Indicates that one of the global URI handling functions was used in a way that is
incompatible with its definition.
20.5.6 NativeError Object Structure
Each of these objects has the structure described below, differing only in the name used as the
constructor
name and in the "name" property of the prototype object.
For each error object, references to NativeError in the definition should be replaced
with the appropriate error object name from 20.5.5 .
20.5.6.1 The NativeError Constructors
Each NativeError constructor :
creates and initializes a new NativeError object when called as a function
rather than as a constructor . A call of the object as a
function is equivalent to calling it as a constructor with the same
arguments. Thus the function call NativeError (…) is equivalent
to the object creation expression new NativeError (…) with the
same arguments.
may be used as the value of an extends clause of a class definition.
Subclass constructors that intend to inherit the
specified NativeError behaviour must include a super call to the
NativeError constructor to create and initialize subclass
instances with an [[ErrorData]] internal slot.
20.5.6.1.1 NativeError ( message [ ,
options ] )
Each NativeError function performs the following steps when called:
If NewTarget is undefined , let newTarget be the
active function object ;
else let newTarget be NewTarget.
Let O be
? OrdinaryCreateFromConstructor (newTarget ,
"%NativeError .prototype%", « [[ErrorData]] »).
If message is not undefined , then
Let msg be ? ToString (message ).
Perform CreateNonEnumerableDataPropertyOrThrow (O ,
"message" , msg ).
Perform ? InstallErrorCause (O ,
options ).
Return O .
The actual value of the string passed in step 2 is
either "%EvalError.prototype%" ,
"%RangeError.prototype%" ,
"%ReferenceError.prototype%" ,
"%SyntaxError.prototype%" ,
"%TypeError.prototype%" , or "%URIError.prototype%"
corresponding to which NativeError constructor is being defined.
20.5.6.2 Properties of the NativeError Constructors
Each NativeError constructor :
has a [[Prototype]] internal slot whose value is %Error% .
has a "name" property whose value is the String value
"NativeError " .
has the following properties:
20.5.6.2.1 NativeError .prototype
The initial value of NativeError .prototype is a
NativeError prototype object (20.5.6.3 ).
Each NativeError constructor has a distinct prototype object.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
false }.
20.5.6.3 Properties of the NativeError Prototype
Objects
Each NativeError prototype object :
is an ordinary object .
is not an Error instance and does not have an [[ErrorData]]
internal slot.
has a [[Prototype]] internal slot whose value is %Error.prototype% .
20.5.6.3.1 NativeError .prototype.constructor
The initial value of the "constructor" property of the prototype for a
given NativeError constructor is the constructor
itself.
20.5.6.3.2 NativeError .prototype.message
The initial value of the "message" property of the prototype for a
given NativeError constructor is the empty String.
20.5.6.3.3 NativeError .prototype.name
The initial value of the "name" property of the prototype for a given
NativeError constructor is the String value consisting of
the name of the constructor (the name used instead of
NativeError ).
20.5.6.4 Properties of NativeError Instances
NativeError instances are ordinary objects that inherit properties from
their NativeError prototype object and have an [[ErrorData]] internal slot whose value is
undefined . The only specified use of [[ErrorData]] is by Object.prototype.toString
(20.1.3.6 ) and
Error.isError (20.5.2.1 ) to identify Error,
AggregateError, or NativeError instances.
20.5.7 AggregateError Objects
20.5.7.1 The AggregateError Constructor
The AggregateError constructor :
is %AggregateError% .
is the initial value of the "AggregateError" property of the
global
object .
creates and initializes a new AggregateError object when called as a function rather
than as a constructor . Thus the function call
AggregateError(…) is equivalent to the object creation expression
new AggregateError(…) with the same arguments.
may be used as the value of an extends clause of a class definition.
Subclass constructors that intend to inherit the
specified AggregateError behaviour must include a super call to the
AggregateError constructor to create and initialize subclass
instances with an [[ErrorData]] internal slot.
20.5.7.1.1 AggregateError ( errors ,
message [ , options ] )
This function performs the following steps when called:
If NewTarget is undefined , let newTarget be the
active function object ;
else let newTarget be NewTarget.
Let O be ? OrdinaryCreateFromConstructor (newTarget ,
"%AggregateError.prototype%" , « [[ErrorData]] »).
If message is not undefined , then
Let msg be ? ToString (message ).
Perform CreateNonEnumerableDataPropertyOrThrow (O ,
"message" , msg ).
Perform ? InstallErrorCause (O ,
options ).
Let errorsList be ? IteratorToList (? GetIterator (errors ,
sync )).
Perform ! DefinePropertyOrThrow (O ,
"errors" , PropertyDescriptor { [[Configurable]] : true , [[Enumerable]] : false , [[Writable]] : true , [[Value]] : CreateArrayFromList (errorsList ) }).
Return O .
20.5.7.2 Properties of the AggregateError Constructor
The AggregateError constructor :
has a [[Prototype]] internal slot whose value is %Error% .
has the following properties:
20.5.7.2.1 AggregateError.prototype
The initial value of AggregateError.prototype is %AggregateError.prototype% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
false }.
20.5.7.3 Properties of the AggregateError Prototype Object
The AggregateError prototype object :
is %AggregateError.prototype% .
is an ordinary object .
is not an Error instance or an AggregateError instance and does not have an [[ErrorData]] internal slot.
has a [[Prototype]] internal slot whose value is %Error.prototype% .
20.5.7.3.1 AggregateError.prototype.constructor
The initial value of AggregateError.prototype.constructor is %AggregateError% .
20.5.7.3.2 AggregateError.prototype.message
The initial value of AggregateError.prototype.message is the empty String.
20.5.7.3.3 AggregateError.prototype.name
The initial value of AggregateError.prototype.name is
"AggregateError" .
20.5.7.4 Properties of AggregateError Instances
AggregateError instances are ordinary objects that inherit properties from
their AggregateError
prototype object and have an [[ErrorData]]
internal slot whose value is undefined . The only specified use of [[ErrorData]] is by Object.prototype.toString
(20.1.3.6 ) and
Error.isError (20.5.2.1 ) to identify Error,
AggregateError, or NativeError instances.
20.5.8 Abstract Operations for Error Objects
20.5.8.1 InstallErrorCause ( O , options )
The abstract operation InstallErrorCause takes arguments O (an Object) and
options (an ECMAScript language value ) and
returns either a normal completion
containing unused or a throw completion . It
is used to create a "cause" property on O when a
"cause" property is present on options . It performs the
following steps when called:
If options is an Object and ? HasProperty (options ,
"cause" ) is true , then
Let cause be ? Get (options ,
"cause" ).
Perform CreateNonEnumerableDataPropertyOrThrow (O ,
"cause" , cause ).
Return unused .
21 Numbers and Dates
21.1 Number Objects
21.1.1 The Number Constructor
The Number constructor :
is %Number% .
is the initial value of the "Number" property of the global
object .
creates and initializes a new Number object when called as a constructor .
performs a type conversion when called as a function rather than as a constructor .
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Number behaviour must include a super call to the Number constructor to
create and initialize the subclass instance with a [[NumberData]]
internal slot.
21.1.1.1 Number ( value )
This function performs the following steps when called:
If value is present, then
Let prim be ? ToNumeric (value ).
If prim is a
BigInt , let n be 𝔽 (ℝ (prim )).
Otherwise, let n be prim .
Else,
Let n be +0 𝔽 .
If NewTarget is undefined , return n .
Let O be ? OrdinaryCreateFromConstructor (NewTarget,
"%Number.prototype%" , « [[NumberData]] »).
Set O .[[NumberData]] to n .
Return O .
21.1.2 Properties of the Number Constructor
The Number constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
21.1.2.1 Number.EPSILON
The value of Number.EPSILON is the Number value for the magnitude
of the difference between 1 and the smallest value greater than 1 that is representable as a
Number value, which is approximately 2.2204460492503130808472633361816 × 10-16 .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.2 Number.isFinite ( number )
This function performs the following steps when called:
If number is not a
Number , return false .
If number is not finite , return false .
Otherwise, return true .
21.1.2.3 Number.isInteger ( number )
This function performs the following steps when called:
If number is an integral Number , return
true .
Return false .
21.1.2.4 Number.isNaN ( number )
This function performs the following steps when called:
If number is not a
Number , return false .
If number is NaN , return true .
Otherwise, return false .
Note
This function differs from the global isNaN function (19.2.3 ) in that it does not convert
its argument to a Number before determining whether it is NaN .
21.1.2.5 Number.isSafeInteger ( number )
Note
An integer
n is a "safe integer " if and
only if the Number value for n is not
the Number value for any other integer .
This function performs the following steps when called:
If number is an integral Number , then
If abs (ℝ (number )) ≤
253 - 1, return true .
Return false .
21.1.2.6 Number.MAX_SAFE_INTEGER
Note
Due to rounding behaviour necessitated by precision limitations of IEEE
754-2019 , the Number value for every
integer
greater than Number.MAX_SAFE_INTEGER is shared with at least one other
integer .
Such large-magnitude integers are therefore not safe ,
and are not guaranteed to be exactly representable as Number values or even to be
distinguishable from each other. For example, both 9007199254740992 and
9007199254740993 evaluate to the Number value
9007199254740992 𝔽 .
The value of Number.MAX_SAFE_INTEGER is
9007199254740991 𝔽 (𝔽 (253 - 1)).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.7 Number.MAX_VALUE
The value of Number.MAX_VALUE is the largest positive finite value of the Number type , which
is approximately 1.7976931348623157 × 10308 .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.8 Number.MIN_SAFE_INTEGER
Note
Due to rounding behaviour necessitated by precision limitations of IEEE
754-2019 , the Number value for every
integer
less than Number.MIN_SAFE_INTEGER is shared with at least one other
integer .
Such large-magnitude integers are therefore not safe ,
and are not guaranteed to be exactly representable as Number values or even to be
distinguishable from each other. For example, both -9007199254740992
and -9007199254740993 evaluate to the Number value
-9007199254740992 𝔽 .
The value of Number.MIN_SAFE_INTEGER is
-9007199254740991 𝔽 (𝔽 (-(253 - 1))).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.9 Number.MIN_VALUE
The value of Number.MIN_VALUE is the smallest positive value of the Number type , which
is approximately 5 × 10-324 .
In the IEEE
754-2019 double precision binary representation, the smallest
possible value is a denormalized number. If an implementation does not support denormalized
values, the value of Number.MIN_VALUE must be the smallest non-zero positive
value that can actually be represented by the implementation.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.10 Number.NaN
The value of Number.NaN is NaN .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.11 Number.NEGATIVE_INFINITY
The value of Number.NEGATIVE_INFINITY is -∞ 𝔽 .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.12 Number.parseFloat ( string )
The initial value of the "parseFloat" property is %parseFloat% .
21.1.2.13 Number.parseInt ( string , radix
)
The initial value of the "parseInt" property is %parseInt% .
21.1.2.14 Number.POSITIVE_INFINITY
The value of Number.POSITIVE_INFINITY is +∞ 𝔽 .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.2.15 Number.prototype
The initial value of Number.prototype is the Number prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.1.3 Properties of the Number Prototype Object
The Number prototype object :
is %Number.prototype% .
is an ordinary
object .
is itself a Number object; it has a [[NumberData]] internal slot
with the value +0 𝔽 .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
Unless explicitly stated otherwise, the methods of the Number prototype object defined below are
not generic and the this value passed to them must be either a Number value
or an object that has a [[NumberData]] internal slot that has been
initialized to a Number value.
The phrase “this Number value” within the specification of a method refers to the result returned
by calling the abstract operation ThisNumberValue with the
this value of the method invocation passed as the argument.
21.1.3.1 Number.prototype.constructor
The initial value of Number.prototype.constructor is %Number% .
21.1.3.2 Number.prototype.toExponential (
fractionDigits )
This method returns a String containing this Number value represented in decimal exponential
notation with one digit before the significand's decimal point and fractionDigits
digits after the significand's decimal point. If fractionDigits is
undefined , it includes as many significand digits as necessary to
uniquely specify the Number (just like in ToString except that in this case the Number is
always output in exponential notation).
It performs the following steps when called:
Let x be ? ThisNumberValue (this
value).
Let f be ? ToIntegerOrInfinity (fractionDigits ).
Assert : If
fractionDigits is undefined , then f is 0.
If x is not finite , return Number::toString (x ,
10).
If f < 0 or f > 100, throw a
RangeError exception.
Set x to ℝ (x ).
Let s be the empty String.
If x < 0, then
Set s to "-" .
Set x to -x .
If x = 0, then
Let m be the String value consisting of f + 1
occurrences of the code unit 0x0030 (DIGIT ZERO).
Let e be 0.
Else,
If fractionDigits is not undefined , then
Let e and n be integers such
that 10f ≤ n <
10f + 1 and for which n ×
10e - f - x is as close
to zero as possible. If there are two such sets of e and
n , pick the e and n for which
n × 10e - f is larger.
Else,
Let
e , n , and ff be integers such that
ff ≥ 0, 10ff ≤ n <
10ff + 1 , 𝔽 (n ×
10e - ff ) is 𝔽 (x ),
and ff is as small as possible. Note that the decimal
representation of n has ff + 1 digits,
n is not divisible by 10, and the least significant digit
of n is not necessarily uniquely determined by these
criteria.
Set f to ff .
Let m be the String value consisting of the digits of the decimal
representation of n (in order, with no leading zeroes).
If f ≠ 0, then
Let a be the first code unit of m .
Let b be the other f code units of m .
Set m to the string-concatenation of
a , "." , and b .
If e = 0, then
Let c be "+" .
Let d be "0" .
Else,
If e > 0, then
Let c be "+" .
Else,
Assert : e < 0.
Let c be "-" .
Set e to -e .
Let d be the String value consisting of the digits of the decimal
representation of e (in order, with no leading zeroes).
Set m to the string-concatenation of
m , "e" , c , and d .
Return the string-concatenation of
s and m .
Note
For implementations that provide more accurate conversions than required by the rules
above, it is recommended that the following alternative version of step 10.b.i
be used as a guideline:
Let e , n , and f be integers such that f ≥ 0,
10f ≤ n < 10f + 1 ,
𝔽 (n × 10e -
f ) is 𝔽 (x ), and f is as
small as possible. If there are multiple possibilities for n ,
choose the value of n for which 𝔽 (n ×
10e - f ) is closest in value to 𝔽 (x ).
If there are two such possible values of n , choose the one that
is even.
21.1.3.3 Number.prototype.toFixed ( fractionDigits )
Note 1
This method returns a String containing this Number value represented in decimal
fixed-point notation with fractionDigits digits after the decimal point.
If fractionDigits is undefined , 0 is assumed.
It performs the following steps when called:
Let x be ? ThisNumberValue (this
value).
Let f be ? ToIntegerOrInfinity (fractionDigits ).
Assert : If
fractionDigits is undefined , then f is 0.
If f is not finite , throw a RangeError
exception.
If f < 0 or f > 100, throw a
RangeError exception.
If x is not finite , return Number::toString (x ,
10).
Set x to ℝ (x ).
Let s be the empty String.
If x < 0, then
Set s to "-" .
Set x to -x .
If x ≥ 1021 , then
Let m be ! ToString (𝔽 (x )).
Else,
Let n be an integer for which n /
10f - x is as close to zero as possible. If
there are two such n , pick the larger n .
If n = 0, let m be "0" ; otherwise
let m be the String value consisting of the digits of the decimal
representation of n (in order, with no leading zeroes).
If f ≠ 0, then
Let k be the length of m .
If k ≤ f , then
Let z be the String value consisting of
f + 1 - k occurrences of the code unit
0x0030 (DIGIT ZERO).
Set m to the string-concatenation
of z and m .
Set k to f + 1.
Let a be the first k - f code units
of m .
Let b be the other f code units of
m .
Set m to the string-concatenation
of a , "." , and b .
Return the string-concatenation of
s and m .
Note 2
The output of toFixed may be more precise than toString for
some values because toString only prints enough significant digits to distinguish
the number from adjacent Number values. For example,
(1000000000000000128).toString() returns
"1000000000000000100" , while
(1000000000000000128).toFixed(0) returns
"1000000000000000128" .
21.1.3.4 Number.prototype.toLocaleString ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method produces a String value that represents this Number value formatted according to
the conventions of the host environment 's current locale. This
method is implementation-defined , and it is
permissible, but not encouraged, for it to return the same thing as toString.
The meanings of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
21.1.3.5 Number.prototype.toPrecision ( precision )
This method returns a String containing this Number value represented either in decimal
exponential notation with one digit before the significand's decimal point and precision - 1 digits after the significand's decimal
point or in decimal fixed notation with precision significant digits. If
precision is undefined , it calls ToString instead.
It performs the following steps when called:
Let x be ? ThisNumberValue (this
value).
If precision is undefined , return ! ToString (x ).
Let p be ? ToIntegerOrInfinity (precision ).
If x is not finite , return Number::toString (x ,
10).
If p < 1 or p > 100, throw a
RangeError exception.
Set x to ℝ (x ).
Let s be the empty String.
If x < 0, then
Set s to the code unit 0x002D (HYPHEN-MINUS).
Set x to -x .
If x = 0, then
Let m be the String value consisting of p occurrences
of the code unit 0x0030 (DIGIT ZERO).
Let e be 0.
Else,
Let e and n be integers such that
10p - 1 ≤ n < 10p
and for which n × 10e - p + 1 -
x is as close to zero as possible. If there are two such sets of
e and n , pick the e and n for
which n × 10e - p + 1 is larger.
Let m be the String value consisting of the digits of the decimal
representation of n (in order, with no leading zeroes).
If e < -6 or e ≥ p , then
Assert : e ≠ 0.
If p ≠ 1, then
Let a be the first code unit of m .
Let b be the other p - 1 code units of
m .
Set m to the string-concatenation
of a , "." , and b .
If e > 0, then
Let c be the code unit 0x002B (PLUS SIGN).
Else,
Assert : e
< 0.
Let c be the code unit 0x002D (HYPHEN-MINUS).
Set e to -e .
Let d be the String value consisting of the digits of the
decimal representation of e (in order, with no leading
zeroes).
Return the string-concatenation
of s , m , the code unit 0x0065 (LATIN SMALL
LETTER E), c , and d .
If e = p - 1, return the string-concatenation of
s and m .
If e ≥ 0, then
Set m to the string-concatenation of
the first e + 1 code units of m , the code unit 0x002E
(FULL STOP), and the remaining p - (e + 1) code units
of m .
Else,
Set m to the string-concatenation of
the code unit 0x0030 (DIGIT ZERO), the code unit 0x002E (FULL STOP),
-(e + 1) occurrences of the code unit 0x0030 (DIGIT ZERO), and
the String m .
Return the string-concatenation of
s and m .
21.1.3.6 Number.prototype.toString ( [ radix ] )
Note
The optional radix should be an integral Number value
in the inclusive interval from
2 𝔽 to 36 𝔽 . If
radix is undefined then
10 𝔽 is used as the value of radix .
This method performs the following steps when called:
Let x be ? ThisNumberValue (this
value).
If radix is undefined , let radixMV be 10.
Else, let radixMV be ? ToIntegerOrInfinity (radix ).
If radixMV is not in the inclusive interval
from 2 to 36, throw a RangeError exception.
Return Number::toString (x ,
radixMV ).
This method is not generic; it throws a TypeError exception if its
this value is not a
Number or a Number object. Therefore, it cannot be transferred to
other kinds of objects for use as a method.
The "length" property of this method is 1 𝔽 .
21.1.3.7 Number.prototype.valueOf ( )
Return ? ThisNumberValue (this
value).
21.1.3.7.1 ThisNumberValue ( value )
The abstract operation ThisNumberValue takes argument value (an ECMAScript language value )
and returns either a normal completion
containing a Number or a throw
completion . It performs the following steps when called:
If value is a
Number , return value .
If value is an Object and value
has a [[NumberData]] internal slot, then
Let n be value .[[NumberData]] .
Assert : n is a
Number .
Return n .
Throw a TypeError exception.
21.1.4 Properties of Number Instances
Number instances are ordinary objects that inherit properties from the
Number prototype
object . Number instances also have a [[NumberData]] internal slot. The [[NumberData]] internal slot is the Number value represented by this
Number object.
21.2 BigInt Objects
21.2.1 The BigInt Constructor
The BigInt constructor :
is %BigInt% .
is the initial value of the "BigInt" property of the global
object .
performs a type conversion when called as a function rather than as a constructor .
is not intended to be used with the new operator or to be subclassed. It may be
used as the value of an extends clause of a class definition but a
super call to the BigInt constructor will cause an exception.
21.2.1.1 BigInt ( value )
This function performs the following steps when called:
If NewTarget is not undefined , throw a
TypeError exception.
Let prim be ? ToPrimitive (value ,
number ).
If prim is a
Number , return ? NumberToBigInt (prim ).
Otherwise, return ? ToBigInt (prim ).
21.2.1.1.1 NumberToBigInt ( number )
The abstract operation NumberToBigInt takes argument number (a Number) and
returns either a normal completion
containing a BigInt or a throw
completion . It performs the following steps when called:
If number is not an integral Number ,
throw a RangeError exception.
Return ℤ (ℝ (number )).
21.2.2 Properties of the BigInt Constructor
The BigInt constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
21.2.2.1 BigInt.asIntN ( bits , bigint )
This function performs the following steps when called:
Set bits to ? ToIndex (bits ).
Set bigint to ? ToBigInt (bigint ).
Let mod be ℝ (bigint ) modulo
2bits .
If mod ≥ 2bits - 1 , return ℤ (mod -
2bits ); otherwise return ℤ (mod ).
21.2.2.2 BigInt.asUintN ( bits , bigint )
This function performs the following steps when called:
Set bits to ? ToIndex (bits ).
Set bigint to ? ToBigInt (bigint ).
Return ℤ (ℝ (bigint )
modulo
2bits ).
21.2.2.3 BigInt.prototype
The initial value of BigInt.prototype is the BigInt prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.2.3 Properties of the BigInt Prototype Object
The BigInt prototype object :
The phrase “this BigInt value” within the specification of a method refers to the result returned
by calling the abstract operation ThisBigIntValue with the
this value of the method invocation passed as the argument.
21.2.3.1 BigInt.prototype.constructor
The initial value of BigInt.prototype.constructor is %BigInt% .
21.2.3.2 BigInt.prototype.toLocaleString ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method produces a String value that represents this BigInt value formatted according to
the conventions of the host environment 's current locale. This
method is implementation-defined , and it is
permissible, but not encouraged, for it to return the same thing as toString.
The meanings of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
21.2.3.3 BigInt.prototype.toString ( [ radix ] )
Note
The optional radix should be an integral Number value
in the inclusive interval from
2 𝔽 to 36 𝔽 . If
radix is undefined then
10 𝔽 is used as the value of radix .
This method performs the following steps when called:
Let x be ? ThisBigIntValue (this
value).
If radix is undefined , let radixMV be 10.
Else, let radixMV be ? ToIntegerOrInfinity (radix ).
If radixMV is not in the inclusive interval
from 2 to 36, throw a RangeError exception.
Return BigInt::toString (x ,
radixMV ).
This method is not generic; it throws a TypeError exception if its
this value is not a
BigInt or a BigInt object. Therefore, it cannot be transferred to
other kinds of objects for use as a method.
21.2.3.4 BigInt.prototype.valueOf ( )
Return ? ThisBigIntValue (this
value).
21.2.3.4.1 ThisBigIntValue ( value )
The abstract operation ThisBigIntValue takes argument value (an ECMAScript language value )
and returns either a normal completion
containing a BigInt or a throw
completion . It performs the following steps when called:
If value is a
BigInt , return value .
If value is an Object and value
has a [[BigIntData]] internal slot, then
Assert : value .[[BigIntData]] is a
BigInt .
Return value .[[BigIntData]] .
Throw a TypeError exception.
21.2.3.5 BigInt.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "BigInt" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
21.2.4 Properties of BigInt Instances
BigInt instances are ordinary objects that inherit properties from the
BigInt prototype
object . BigInt instances also have a [[BigIntData]] internal slot. The [[BigIntData]] internal slot is the BigInt value represented by this
BigInt object.
21.3 The Math Object
The Math object:
is %Math% .
is the initial value of the "Math" property of the global
object .
is an ordinary
object .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is not a function
object .
does not have a [[Construct]] internal method; it cannot be used as a
constructor
with the new operator.
does not have a [[Call]] internal method; it cannot be invoked as a
function.
Note
In this specification, the phrase “the Number value for x ” has a
technical meaning defined in 6.1.6.1 .
21.3.1 Value Properties of the Math Object
21.3.1.1 Math.E
The Number
value for e , the base of the natural logarithms, which is
approximately 2.7182818284590452354.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.3.1.2 Math.LN10
The Number
value for the natural logarithm of 10, which is approximately
2.302585092994046.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.3.1.3 Math.LN2
The Number
value for the natural logarithm of 2, which is approximately
0.6931471805599453.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.3.1.4 Math.LOG10E
The Number
value for the base-10 logarithm of e , the base of the natural
logarithms; this value is approximately 0.4342944819032518.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
The value of Math.LOG10E is approximately the reciprocal of the value of
Math.LN10.
21.3.1.5 Math.LOG2E
The Number
value for the base-2 logarithm of e , the base of the natural
logarithms; this value is approximately 1.4426950408889634.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
The value of Math.LOG2E is approximately the reciprocal of the value of
Math.LN2.
21.3.1.6 Math.PI
The Number
value for π, the ratio of the circumference of a circle to its
diameter, which is approximately 3.1415926535897932.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.3.1.7 Math.SQRT1_2
The Number
value for the square root of ½, which is approximately
0.7071067811865476.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
The value of Math.SQRT1_2 is approximately the reciprocal of the value
of Math.SQRT2.
21.3.1.8 Math.SQRT2
The Number
value for the square root of 2, which is approximately
1.4142135623730951.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.3.1.9 Math [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Math" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
21.3.2 Function Properties of the Math Object
Note
The behaviour of the functions acos, acosh, asin,
asinh, atan, atanh, atan2,
cbrt, cos, cosh, exp,
expm1, hypot, log, log1p,
log2, log10, pow, random,
sin, sinh, tan, and tanh is not
precisely specified here except to require specific results for certain argument values
that represent boundary cases of interest. For other argument values, these functions
are intended to compute approximations to the results of familiar mathematical
functions, but some latitude is allowed in the choice of approximation algorithms. The
general intent is that an implementer should be able to use the same mathematical
library for ECMAScript on a given hardware platform that is available to C programmers
on that platform.
Although the choice of algorithms is left to the implementation, it is recommended (but
not specified by this standard) that implementations use the approximation algorithms
for IEEE
754-2019 arithmetic contained in fdlibm, the freely
distributable mathematical library from Sun Microsystems (http://www.netlib.org/fdlibm ).
21.3.2.1 Math.abs ( x )
This function returns the absolute value of x ; the result has the same magnitude
as x but has positive sign.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is NaN , return NaN .
If n is -0 𝔽 , return
+0 𝔽 .
If n is -∞ 𝔽 , return
+∞ 𝔽 .
If n < -0 𝔽 , return -n .
Return n .
21.3.2.2 Math.acos ( x )
This function returns the inverse cosine of x . The result is expressed in radians
and is in the inclusive interval from
+0 𝔽 to 𝔽 (π).
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is NaN , n >
1 𝔽 , or n <
-1 𝔽 , return NaN .
If n is 1 𝔽 , return
+0 𝔽 .
Return an implementation-approximated
Number value representing the inverse cosine of ℝ (n ).
21.3.2.3 Math.acosh ( x )
This function returns the inverse hyperbolic cosine of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is either NaN or
+∞ 𝔽 , return n .
If n is 1 𝔽 , return
+0 𝔽 .
If n < 1 𝔽 , return
NaN .
Return an implementation-approximated
Number value representing the inverse hyperbolic cosine of ℝ (n ).
21.3.2.4 Math.asin ( x )
This function returns the inverse sine of x . The result is expressed in radians
and is in the inclusive interval from 𝔽 (-π / 2) to 𝔽 (π / 2).
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n > 1 𝔽 or n <
-1 𝔽 , return NaN .
Return an implementation-approximated
Number value representing the inverse sine of ℝ (n ).
21.3.2.5 Math.asinh ( x )
This function returns the inverse hyperbolic sine of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
Return an implementation-approximated
Number value representing the inverse hyperbolic sine of ℝ (n ).
21.3.2.6 Math.atan ( x )
This function returns the inverse tangent of x . The result is expressed in radians
and is in the inclusive interval from 𝔽 (-π / 2) to 𝔽 (π / 2).
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n is +∞ 𝔽 , return an implementation-approximated
Number value representing π / 2.
If n is -∞ 𝔽 , return an implementation-approximated
Number value representing -π / 2.
Return an implementation-approximated
Number value representing the inverse tangent of ℝ (n ).
21.3.2.7 Math.atanh ( x )
This function returns the inverse hyperbolic tangent of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n > 1 𝔽 or n <
-1 𝔽 , return NaN .
If n is 1 𝔽 , return
+∞ 𝔽 .
If n is -1 𝔽 , return
-∞ 𝔽 .
Return an implementation-approximated
Number value representing the inverse hyperbolic tangent of ℝ (n ).
21.3.2.8 Math.atan2 ( y , x )
This function returns the inverse tangent of the quotient y / x of the arguments y and
x , where the signs of y and x are used to determine the
quadrant of the result. Note that it is intentional and traditional for the two-argument
inverse tangent function that the argument named y be first and the argument
named x be second. The result is expressed in radians and is in the inclusive
interval from -π to +π.
It performs the following steps when called:
Let ny be ? ToNumber (y ).
Let nx be ? ToNumber (x ).
If ny is NaN or nx is
NaN , return NaN .
If ny is +∞ 𝔽 , then
If nx is +∞ 𝔽 , return an implementation-approximated
Number value representing π / 4.
If nx is -∞ 𝔽 , return an implementation-approximated
Number value representing 3π / 4.
Return an implementation-approximated
Number value representing π / 2.
If ny is -∞ 𝔽 , then
If nx is +∞ 𝔽 , return an implementation-approximated
Number value representing -π / 4.
If nx is -∞ 𝔽 , return an implementation-approximated
Number value representing -3π / 4.
Return an implementation-approximated
Number value representing -π / 2.
If ny is +0 𝔽 , then
If nx > +0 𝔽 or nx is
+0 𝔽 , return
+0 𝔽 .
Return an implementation-approximated
Number value representing π.
If ny is -0 𝔽 , then
If nx > +0 𝔽 or nx is
+0 𝔽 , return
-0 𝔽 .
Return an implementation-approximated
Number value representing -π.
Assert :
ny is finite and is neither
+0 𝔽 nor -0 𝔽 .
If ny > +0 𝔽 , then
If nx is +∞ 𝔽 , return
+0 𝔽 .
If nx is -∞ 𝔽 , return an implementation-approximated
Number value representing π.
If nx is either +0 𝔽 or
-0 𝔽 , return an implementation-approximated
Number value representing π / 2.
If ny < -0 𝔽 , then
If nx is +∞ 𝔽 , return
-0 𝔽 .
If nx is -∞ 𝔽 , return an implementation-approximated
Number value representing -π.
If nx is either +0 𝔽 or
-0 𝔽 , return an implementation-approximated
Number value representing -π / 2.
Assert :
nx is finite and is neither
+0 𝔽 nor -0 𝔽 .
Let r be the inverse tangent of abs (ℝ (ny ) / ℝ (nx )).
If nx < -0 𝔽 , then
If ny > +0 𝔽 , set r
to π - r .
Else, set r to -π + r .
Else,
If ny < -0 𝔽 , set r
to -r .
Return an implementation-approximated
Number value representing r .
21.3.2.9 Math.cbrt ( x )
This function returns the cube root of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
Return an implementation-approximated
Number value representing the cube root of ℝ (n ).
21.3.2.10 Math.ceil ( x )
This function returns the smallest (closest to -∞) integral Number value that is
not less than x . If x is already an integral Number , the result is
x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
If n < -0 𝔽 and n >
-1 𝔽 , return -0 𝔽 .
If n is an integral Number , return n .
Return the smallest (closest to -∞) integral Number value
that is not less than n .
Note
The value of Math.ceil(x) is the same as the value of
-Math.floor(-x).
21.3.2.11 Math.clz32 ( x )
This function performs the following steps when called:
Let n be ? ToUint32 (x ).
Let p be the number of leading zero bits in the unsigned 32-bit binary
representation of n .
Return 𝔽 (p ).
Note
If n is either +0 𝔽 or
-0 𝔽 , this method returns
32 𝔽 . If the most significant bit of the 32-bit binary
encoding of n is 1, this method returns
+0 𝔽 .
21.3.2.12 Math.cos ( x )
This function returns the cosine of x . The argument is expressed in radians.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite , return NaN .
If n is either +0 𝔽 or
-0 𝔽 , return 1 𝔽 .
Return an implementation-approximated
Number value representing the cosine of ℝ (n ).
21.3.2.13 Math.cosh ( x )
This function returns the hyperbolic cosine of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is NaN , return NaN .
If n is either +∞ 𝔽 or
-∞ 𝔽 , return +∞ 𝔽 .
If n is either +0 𝔽 or
-0 𝔽 , return 1 𝔽 .
Return an implementation-approximated
Number value representing the hyperbolic cosine of ℝ (n ).
Note
The value of Math.cosh(x) is the same as the value of
(Math.exp(x) + Math.exp(-x)) / 2.
21.3.2.14 Math.exp ( x )
This function returns the exponential function of x (e raised to the
power of x , where e is the base of the natural logarithms).
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is either NaN or
+∞ 𝔽 , return n .
If n is either +0 𝔽 or
-0 𝔽 , return 1 𝔽 .
If n is -∞ 𝔽 , return
+0 𝔽 .
Return an implementation-approximated
Number value representing the exponential function of ℝ (n ).
21.3.2.15 Math.expm1 ( x )
This function returns the result of subtracting 1 from the exponential function of
x (e raised to the power of x , where e is the
base of the natural logarithms). The result is computed in a way that is accurate even when
the value of x is close to 0.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , -0 𝔽 , or
+∞ 𝔽 , return n .
If n is -∞ 𝔽 , return
-1 𝔽 .
Let exp be the exponential function of ℝ (n ).
Return an implementation-approximated
Number value representing exp - 1.
21.3.2.16 Math.floor ( x )
This function returns the greatest (closest to +∞) integral Number value that is
not greater than x . If x is already an integral
Number , the result is x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
If n < 1 𝔽 and n >
+0 𝔽 , return +0 𝔽 .
If n is an integral Number , return n .
Return the greatest (closest to +∞) integral Number value
that is not greater than n .
Note
The value of Math.floor(x) is the same as the value of
-Math.ceil(-x).
21.3.2.17 Math.fround ( x )
This function performs the following steps when called:
Let n be ? ToNumber (x ).
If n is NaN , return NaN .
If n is one of +0 𝔽 ,
-0 𝔽 , +∞ 𝔽 , or
-∞ 𝔽 , return n .
Let n32 be the result of converting n to IEEE
754-2019 binary32 format using roundTiesToEven mode.
Let n64 be the result of converting n32 to IEEE
754-2019 binary64 format.
Return the ECMAScript Number value corresponding to n64 .
21.3.2.18 Math.f16round ( x )
This function performs the following steps when called:
Let n be ? ToNumber (x ).
If n is NaN , return NaN .
If n is one of +0 𝔽 ,
-0 𝔽 , +∞ 𝔽 , or
-∞ 𝔽 , return n .
Let n16 be the result of converting n to IEEE
754-2019 binary16 format using roundTiesToEven mode.
Let n64 be the result of converting n16 to IEEE
754-2019 binary64 format.
Return the ECMAScript Number value corresponding to n64 .
Note
This operation is not the same as casting to binary32 and then to binary16 because of
the possibility of double-rounding: consider the number k =
1.00048828125000022204 𝔽 , for example, for which
Math.f16round(k ) is 1.0009765625 𝔽 , but
Math.f16round(Math.fround(k )) is 1 𝔽 .
Not all platforms provide native support for casting from binary64 to binary16. There
are various libraries which can provide this, including the MIT-licensed half library. Alternatively, it is
possible to first cast from binary64 to binary32 under roundTiesToEven and then
check whether the result could lead to incorrect double-rounding. The cases which
could can be handled explicitly by adjusting the mantissa of the binary32 value so
that it is the value which would be produced by performing the initial cast under
roundTiesToOdd. Casting the adjusted value to binary16 under roundTiesToEven then
produces the correct value.
21.3.2.19 Math.hypot ( ...args )
Given zero or more arguments, this function returns the square root of the sum of squares of
its arguments.
It performs the following steps when called:
Let coerced be a new empty List .
For each element arg of args , do
Let n be ? ToNumber (arg ).
Append n to coerced .
For each element number of coerced , do
If number is either +∞ 𝔽 or
-∞ 𝔽 , return
+∞ 𝔽 .
Let onlyZero be true .
For each element number of coerced , do
If number is NaN , return
NaN .
If number is neither +0 𝔽 nor
-0 𝔽 , set onlyZero to
false .
If onlyZero is true , return
+0 𝔽 .
Return an implementation-approximated
Number value representing the square root of the sum of squares of the mathematical values of the
elements of coerced .
The "length" property of this function is
2 𝔽 .
Note
Implementations should take care to avoid the loss of precision from overflows and
underflows that are prone to occur in naive implementations when this function is
called with two or more arguments.
21.3.2.20 Math.imul ( x , y )
This function performs the following steps when called:
Let a be ℝ (? ToUint32 (x )).
Let b be ℝ (? ToUint32 (y )).
Let product be (a × b ) modulo 232 .
If product ≥ 231 , return 𝔽 (product -
232 ); otherwise return 𝔽 (product ).
21.3.2.21 Math.log ( x )
This function returns the natural logarithm of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is either NaN or
+∞ 𝔽 , return n .
If n is 1 𝔽 , return
+0 𝔽 .
If n is either +0 𝔽 or
-0 𝔽 , return -∞ 𝔽 .
If n < -0 𝔽 , return
NaN .
Return an implementation-approximated
Number value representing the natural logarithm of ℝ (n ).
21.3.2.22 Math.log1p ( x )
This function returns the natural logarithm of 1 + x . The result is computed in a
way that is accurate even when the value of x is close to zero.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , -0 𝔽 , or
+∞ 𝔽 , return n .
If n is -1 𝔽 , return
-∞ 𝔽 .
If n < -1 𝔽 , return
NaN .
Return an implementation-approximated
Number value representing the natural logarithm of 1 + ℝ (n ).
21.3.2.23 Math.log10 ( x )
This function returns the base 10 logarithm of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is either NaN or
+∞ 𝔽 , return n .
If n is 1 𝔽 , return
+0 𝔽 .
If n is either +0 𝔽 or
-0 𝔽 , return -∞ 𝔽 .
If n < -0 𝔽 , return
NaN .
Return an implementation-approximated
Number value representing the base 10 logarithm of ℝ (n ).
21.3.2.24 Math.log2 ( x )
This function returns the base 2 logarithm of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is either NaN or
+∞ 𝔽 , return n .
If n is 1 𝔽 , return
+0 𝔽 .
If n is either +0 𝔽 or
-0 𝔽 , return -∞ 𝔽 .
If n < -0 𝔽 , return
NaN .
Return an implementation-approximated
Number value representing the base 2 logarithm of ℝ (n ).
21.3.2.25 Math.max ( ...args )
Given zero or more arguments, this function calls ToNumber on each of the arguments
and returns the largest of the resulting values.
It performs the following steps when called:
Let coerced be a new empty List .
For each element arg of args , do
Let n be ? ToNumber (arg ).
Append n to coerced .
Let highest be -∞ 𝔽 .
For each element number of coerced , do
If number is NaN , return
NaN .
If number is +0 𝔽 and
highest is -0 𝔽 , set
highest to +0 𝔽 .
If number > highest , set highest to
number .
Return highest .
Note
The comparison of values to determine the largest value is done using the IsLessThan algorithm except that
+0 𝔽 is considered to be larger than
-0 𝔽 .
The "length" property of this function is
2 𝔽 .
21.3.2.26 Math.min ( ...args )
Given zero or more arguments, this function calls ToNumber on each of the arguments
and returns the smallest of the resulting values.
It performs the following steps when called:
Let coerced be a new empty List .
For each element arg of args , do
Let n be ? ToNumber (arg ).
Append n to coerced .
Let lowest be +∞ 𝔽 .
For each element number of coerced , do
If number is NaN , return
NaN .
If number is -0 𝔽 and
lowest is +0 𝔽 , set
lowest to -0 𝔽 .
If number < lowest , set lowest to
number .
Return lowest .
Note
The comparison of values to determine the largest value is done using the IsLessThan algorithm except that
+0 𝔽 is considered to be larger than
-0 𝔽 .
The "length" property of this function is
2 𝔽 .
21.3.2.27 Math.pow ( base , exponent )
This function performs the following steps when called:
Set base to ? ToNumber (base ).
Set exponent to ? ToNumber (exponent ).
Return Number::exponentiate (base ,
exponent ).
21.3.2.28 Math.random ( )
This function returns a Number value with positive sign, greater than or equal to
+0 𝔽 but strictly less than 1 𝔽 ,
chosen randomly or pseudo randomly with approximately uniform distribution over that range,
using an implementation-defined algorithm or
strategy.
Each Math.random function created for distinct realms must produce a distinct sequence
of values from successive calls.
21.3.2.29 Math.round ( x )
This function returns the Number value that is closest to x and is integral. If
two integral
Numbers are equally close to x , then the result is the
Number value that is closer to +∞. If x is already integral, the result is
x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is an integral
Number , return n .
If n < 0.5 𝔽 and n >
+0 𝔽 , return +0 𝔽 .
If n < -0 𝔽 and n ≥
-0.5 𝔽 , return -0 𝔽 .
Return the integral Number closest to
n , preferring the Number closer to +∞ in the case of a tie.
Note 1
Math.round(3.5) returns 4, but Math.round(-3.5) returns -3.
Note 2
The value of Math.round(x) is not always the same as the value of
Math.floor(x + 0.5). When x is
-0 𝔽 or x is less than
-0 𝔽 but greater than or equal to
-0.5 𝔽 , Math.round(x) returns
-0 𝔽 , but Math.floor(x + 0.5) returns
+0 𝔽 . Math.round(x) may also differ from
the value of Math.floor(x + 0.5)because of internal rounding when
computing x + 0.5.
21.3.2.30 Math.sign ( x )
This function returns the sign of x , indicating whether x is positive,
negative, or zero.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n < -0 𝔽 , return
-1 𝔽 .
Return 1 𝔽 .
21.3.2.31 Math.sin ( x )
This function returns the sine of x . The argument is expressed in radians.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n is either +∞ 𝔽 or
-∞ 𝔽 , return NaN .
Return an implementation-approximated
Number value representing the sine of ℝ (n ).
21.3.2.32 Math.sinh ( x )
This function returns the hyperbolic sine of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
Return an implementation-approximated
Number value representing the hyperbolic sine of ℝ (n ).
Note
The value of Math.sinh(x) is the same as the value of
(Math.exp(x) - Math.exp(-x)) / 2.
21.3.2.33 Math.sqrt ( x )
This function returns the square root of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , -0 𝔽 , or
+∞ 𝔽 , return n .
If n < -0 𝔽 , return
NaN .
Return 𝔽 (the
square root of ℝ (n )).
21.3.2.34 Math.tan ( x )
This function returns the tangent of x . The argument is expressed in radians.
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n is either +∞ 𝔽 or
-∞ 𝔽 , return NaN .
Return an implementation-approximated
Number value representing the tangent of ℝ (n ).
21.3.2.35 Math.tanh ( x )
This function returns the hyperbolic tangent of x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is one of NaN ,
+0 𝔽 , or -0 𝔽 , return
n .
If n is +∞ 𝔽 , return
1 𝔽 .
If n is -∞ 𝔽 , return
-1 𝔽 .
Return an implementation-approximated
Number value representing the hyperbolic tangent of ℝ (n ).
Note
The value of Math.tanh(x) is the same as the value of
(Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)).
21.3.2.36 Math.trunc ( x )
This function returns the integral part of the number x , removing any fractional
digits. If x is already integral, the result is x .
It performs the following steps when called:
Let n be ? ToNumber (x ).
If n is not finite or n is either
+0 𝔽 or -0 𝔽 , return
n .
If n < 1 𝔽 and n >
+0 𝔽 , return +0 𝔽 .
If n < -0 𝔽 and n >
-1 𝔽 , return -0 𝔽 .
Return the integral Number nearest n
in the direction of +0 𝔽 .
21.4 Date Objects
21.4.1 Overview of Date Objects and Definitions of Abstract
Operations
The following abstract operations
operate on time values (defined in 21.4.1.1 ). Note that, in every
case, if any argument to one of these functions is NaN , the result will be
NaN .
21.4.1.1 Time Values and Time Range
Time measurement in ECMAScript is analogous to time measurement in POSIX, in particular
sharing definition in terms of the proleptic Gregorian calendar, an epoch of midnight at the beginning of 1 January 1970 UTC, and an
accounting of every day as comprising exactly 86,400 seconds (each of which is 1000
milliseconds long).
An ECMAScript time value is a Number , either
a finite integral
Number representing an instant in time to millisecond precision or
NaN representing no specific instant. A time value that is a multiple of
24 × 60 × 60 × 1000 = 86,400,000 (i.e., is 86,400,000 ×
d for some integer d ) represents the instant at the
start of the UTC day that follows the epoch by d whole UTC days (preceding the
epoch for negative
d ). Every other finite time value t is defined relative to
the greatest preceding time value s that is such a multiple, and represents the
instant that occurs within the same UTC day as s but follows it by (t
- s ) milliseconds.
Time values do not account for UTC leap seconds—there are no time values representing
instants within positive leap seconds, and there are time values representing instants
removed from the UTC timeline by negative leap seconds. However, the definition of time
values nonetheless yields piecewise alignment with UTC, with discontinuities only at leap
second boundaries and zero difference outside of leap seconds.
A Number can exactly represent all integers from -9,007,199,254,740,992 to
9,007,199,254,740,992 (21.1.2.8 and 21.1.2.6 ). A time value supports
a slightly smaller range of -8,640,000,000,000,000 to 8,640,000,000,000,000 milliseconds.
This yields a supported time value range of exactly -100,000,000 days to 100,000,000 days
relative to midnight at the beginning of 1 January 1970 UTC.
The exact moment of midnight at the beginning of 1 January 1970 UTC is represented by the
time value +0 𝔽 .
Note
In the proleptic Gregorian calendar, leap years are precisely those which are both
divisible by 4 and either divisible by 400 or not divisible by 100.
The 400 year cycle of the proleptic Gregorian calendar contains 97 leap years. This
yields an average of 365.2425 days per year, which is 31,556,952,000 milliseconds.
Therefore, the maximum range a Number could represent exactly with millisecond
precision is approximately -285,426 to 285,426 years relative to 1970. The smaller
range supported by a time value as specified in this section is approximately
-273,790 to 273,790 years relative to 1970.
21.4.1.2 Time-related Constants
These constants are referenced by algorithms in the following sections.
HoursPerDay = 24
MinutesPerHour = 60
SecondsPerMinute = 60
msPerSecond = 1000 𝔽
21.4.1.3 Day ( t )
The abstract operation Day takes argument t (a finite time value ) and returns an
integral
Number . It returns the day number of the day in which t
falls. It performs the following steps when called:
Return 𝔽 (floor (ℝ (t / msPerDay ))).
21.4.1.4 TimeWithinDay ( t )
The abstract operation TimeWithinDay takes argument t (a finite time value ) and returns an
integral
Number in the interval from +0 𝔽
(inclusive) to msPerDay (exclusive). It returns the number of
milliseconds since the start of the day in which t falls. It performs the
following steps when called:
Return 𝔽 (ℝ (t ) modulo
ℝ (msPerDay )).
21.4.1.5 DaysInYear ( y )
The abstract operation DaysInYear takes argument y (an integral
Number ) and returns 365 𝔽 or
366 𝔽 . It returns the number of days in year y .
Leap years have 366 days; all other years have 365. It performs the following steps when
called:
Let ry be ℝ (y ).
If (ry modulo 400) = 0, return
366 𝔽 .
If (ry modulo 100) = 0, return
365 𝔽 .
If (ry modulo 4) = 0, return
366 𝔽 .
Return 365 𝔽 .
21.4.1.6 DayFromYear ( y )
The abstract operation DayFromYear takes argument y (an integral
Number ) and returns an integral Number . It returns
the day number of the first day of year y . It performs the following steps when
called:
Let ry be ℝ (y ).
NOTE: In the following steps,
numYears1 , numYears4 , numYears100 , and
numYears400 represent the number of years divisible by 1, 4, 100, and
400, respectively, that occur between the epoch and the start of year y . The
number is negative if y is before the epoch .
Let numYears1 be (ry - 1970).
Let numYears4 be floor ((ry - 1969) / 4).
Let numYears100 be floor ((ry - 1901) / 100).
Let numYears400 be floor ((ry - 1601) / 400).
Return 𝔽 (365 ×
numYears1 + numYears4 - numYears100 +
numYears400 ).
21.4.1.7 TimeFromYear ( y )
The abstract operation TimeFromYear takes argument y (an integral
Number ) and returns a time value . It returns the
time value of the start of
year y . It performs the following steps when called:
Return msPerDay × DayFromYear (y ).
21.4.1.8 YearFromTime ( t )
The abstract operation YearFromTime takes argument t (a finite time value ) and returns an
integral
Number . It returns the year in which t falls. It performs
the following steps when called:
Return the largest integral Number y (closest
to +∞) such that TimeFromYear (y ) ≤
t .
21.4.1.9 DayWithinYear ( t )
The abstract operation DayWithinYear takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 365 𝔽 . It performs the
following steps when called:
Return Day (t ) - DayFromYear (YearFromTime (t )).
21.4.1.10 InLeapYear ( t )
The abstract operation InLeapYear takes argument t (a finite time value ) and returns
+0 𝔽 or 1 𝔽 . It returns
1 𝔽 if t is within a leap year and
+0 𝔽 otherwise. It performs the following steps when called:
If DaysInYear (YearFromTime (t )) is
366 𝔽 , return 1 𝔽 ; else
return +0 𝔽 .
21.4.1.11 MonthFromTime ( t )
The abstract operation MonthFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 11 𝔽 . It returns a
Number identifying the month in which t falls. A month value of
+0 𝔽 specifies January; 1 𝔽
specifies February; 2 𝔽 specifies March;
3 𝔽 specifies April; 4 𝔽
specifies May; 5 𝔽 specifies June;
6 𝔽 specifies July; 7 𝔽
specifies August; 8 𝔽 specifies September;
9 𝔽 specifies October; 10 𝔽
specifies November; and 11 𝔽 specifies December. Note that
MonthFromTime(+0 𝔽 ) =
+0 𝔽 , corresponding to Thursday, 1 January 1970.
It performs the following steps when called:
Let inLeapYear be InLeapYear (t ).
Let dayWithinYear be DayWithinYear (t ).
If dayWithinYear < 31 𝔽 , return
+0 𝔽 .
If dayWithinYear < 59 𝔽 +
inLeapYear , return 1 𝔽 .
If dayWithinYear < 90 𝔽 +
inLeapYear , return 2 𝔽 .
If dayWithinYear < 120 𝔽 +
inLeapYear , return 3 𝔽 .
If dayWithinYear < 151 𝔽 +
inLeapYear , return 4 𝔽 .
If dayWithinYear < 181 𝔽 +
inLeapYear , return 5 𝔽 .
If dayWithinYear < 212 𝔽 +
inLeapYear , return 6 𝔽 .
If dayWithinYear < 243 𝔽 +
inLeapYear , return 7 𝔽 .
If dayWithinYear < 273 𝔽 +
inLeapYear , return 8 𝔽 .
If dayWithinYear < 304 𝔽 +
inLeapYear , return 9 𝔽 .
If dayWithinYear < 334 𝔽 +
inLeapYear , return 10 𝔽 .
Assert :
dayWithinYear < 365 𝔽 +
inLeapYear .
Return 11 𝔽 .
21.4.1.12 DateFromTime ( t )
The abstract operation DateFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
1 𝔽 to 31 𝔽 . It returns the day
of the month in which t falls. It performs the following steps when called:
Let inLeapYear be InLeapYear (t ).
Let dayWithinYear be DayWithinYear (t ).
Let month be MonthFromTime (t ).
If month is +0 𝔽 , return
dayWithinYear + 1 𝔽 .
If month is 1 𝔽 , return
dayWithinYear - 30 𝔽 .
If month is 2 𝔽 , return
dayWithinYear - 58 𝔽 -
inLeapYear .
If month is 3 𝔽 , return
dayWithinYear - 89 𝔽 -
inLeapYear .
If month is 4 𝔽 , return
dayWithinYear - 119 𝔽 -
inLeapYear .
If month is 5 𝔽 , return
dayWithinYear - 150 𝔽 -
inLeapYear .
If month is 6 𝔽 , return
dayWithinYear - 180 𝔽 -
inLeapYear .
If month is 7 𝔽 , return
dayWithinYear - 211 𝔽 -
inLeapYear .
If month is 8 𝔽 , return
dayWithinYear - 242 𝔽 -
inLeapYear .
If month is 9 𝔽 , return
dayWithinYear - 272 𝔽 -
inLeapYear .
If month is 10 𝔽 , return
dayWithinYear - 303 𝔽 -
inLeapYear .
Assert :
month is 11 𝔽 .
Return dayWithinYear - 333 𝔽 -
inLeapYear .
21.4.1.13 WeekDay ( t )
The abstract operation WeekDay takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 6 𝔽 . It returns a Number
identifying the day of the week in which t falls. A weekday value of
+0 𝔽 specifies Sunday; 1 𝔽
specifies Monday; 2 𝔽 specifies Tuesday;
3 𝔽 specifies Wednesday; 4 𝔽
specifies Thursday; 5 𝔽 specifies Friday; and
6 𝔽 specifies Saturday. Note that WeekDay(+0 𝔽 ) =
4 𝔽 , corresponding to Thursday, 1 January 1970.
It performs the following steps when called:
Return 𝔽 (ℝ (Day (t ) +
4 𝔽 ) modulo 7).
21.4.1.14 HourFromTime ( t )
The abstract operation HourFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 23 𝔽 . It returns the
hour of the day in which t falls. It performs the following steps when called:
Return 𝔽 (floor (ℝ (t / msPerHour )) modulo HoursPerDay ).
21.4.1.15 MinFromTime ( t )
The abstract operation MinFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 59 𝔽 . It returns the
minute of the hour in which t falls. It performs the following steps when called:
Return 𝔽 (floor (ℝ (t / msPerMinute )) modulo MinutesPerHour ).
21.4.1.16 SecFromTime ( t )
The abstract operation SecFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 59 𝔽 . It returns the
second of the minute in which t falls. It performs the following steps when
called:
Return 𝔽 (floor (ℝ (t / msPerSecond )) modulo SecondsPerMinute ).
21.4.1.17 msFromTime ( t )
The abstract operation msFromTime takes argument t (a finite time value ) and returns an
integral
Number in the inclusive interval from
+0 𝔽 to 999 𝔽 . It returns the
millisecond of the second in which t falls. It performs the following steps when
called:
Return 𝔽 (ℝ (t ) modulo
ℝ (msPerSecond )).
21.4.1.18 GetUTCEpochNanoseconds ( year ,
month , day , hour , minute , second ,
millisecond , microsecond , nanosecond )
The abstract operation GetUTCEpochNanoseconds takes arguments year (an integer ),
month (an integer in the inclusive interval from 1
to 12), day (an integer in the inclusive interval from 1
to 31), hour (an integer in the inclusive interval from 0
to 23), minute (an integer in the inclusive interval from 0
to 59), second (an integer in the inclusive interval from 0
to 59), millisecond (an integer in the inclusive interval from 0
to 999), microsecond (an integer in the inclusive interval from 0
to 999), and nanosecond (an integer in the inclusive interval from 0
to 999) and returns a BigInt. The returned value represents a number of nanoseconds since
the epoch that
corresponds to the given ISO 8601 calendar date and wall-clock time in UTC. It performs the
following steps when called:
Let date be MakeDay (𝔽 (year ), 𝔽 (month - 1),
𝔽 (day )).
Let time be MakeTime (𝔽 (hour ), 𝔽 (minute ),
𝔽 (second ), 𝔽 (millisecond )).
Let ms be MakeDate (date ,
time ).
Assert :
ms is an integral Number .
Return ℤ (ℝ (ms ) ×
106 + microsecond × 103 + nanosecond ).
21.4.1.19 Time Zone Identifiers
Time zones in ECMAScript are represented by time zone identifiers , which are Strings composed entirely of code
units in the inclusive interval from 0x0000 to 0x007F.
Time zones supported by an ECMAScript implementation may be available named time zones ,
represented by the [[Identifier]] field of the Time Zone Identifier Records
returned by AvailableNamedTimeZoneIdentifiers ,
or offset time zones , represented by
Strings for which IsTimeZoneOffsetString returns
true .
A primary time zone
identifier is the preferred identifier for an available named time zone.
A non-primary time zone
identifier is an identifier for an available named time zone that is not a primary
time zone identifier.
An available named time
zone identifier is either a primary time zone identifier or a non-primary time
zone identifier.
Each available named time zone identifier is associated with exactly one available named
time zone.
Each available named time zone is associated with exactly one primary time zone identifier
and zero or more non-primary time zone identifiers.
ECMAScript implementations must support an available named time zone with the identifier
"UTC" , which must be the primary time zone identifier for the UTC time
zone.
In addition, implementations may support any number of other available named time zones.
Implementations that follow the requirements for time zones as described in the ECMA-402
Internationalization API specification are called time zone aware .
Time zone aware implementations must support available named time zones corresponding to the
Zone and Link names of the IANA Time Zone Database, and only such names.
In time zone aware implementations, a primary time zone identifier is a Zone name, and a
non-primary time zone identifier is a Link name, respectively, in the IANA Time Zone
Database except as specifically overridden by AvailableNamedTimeZoneIdentifiers
as specified in the ECMA-402 specification.
Implementations that do not support the entire IANA Time Zone Database are still recommended
to use IANA Time Zone Database names as identifiers to represent time zones.
21.4.1.20 GetNamedTimeZoneEpochNanoseconds (
timeZoneIdentifier , year , month , day ,
hour , minute , second , millisecond ,
microsecond , nanosecond )
The implementation-defined abstract
operation GetNamedTimeZoneEpochNanoseconds takes arguments timeZoneIdentifier (a
String), year (an integer ), month (an integer in the
inclusive
interval from 1 to 12), day (an integer in the inclusive
interval from 1 to 31), hour (an integer in the inclusive
interval from 0 to 23), minute (an integer in the
inclusive
interval from 0 to 59), second (an integer in the
inclusive
interval from 0 to 59), millisecond (an integer in the
inclusive
interval from 0 to 999), microsecond (an integer in the
inclusive
interval from 0 to 999), and nanosecond (an integer in the
inclusive
interval from 0 to 999) and returns a List of BigInts.
Each value in the returned List
represents a number of nanoseconds since the epoch that corresponds to the given ISO 8601 calendar
date and wall-clock time in the named time zone identified by timeZoneIdentifier .
When the input represents a local time occurring more than once because of a negative time
zone transition (e.g. when daylight saving time ends or the time zone offset is decreased
due to a time zone rule change), the returned List will have more
than one element and will be sorted by ascending numerical value.
When the input represents a local time skipped because of a positive time zone transition
(e.g. when daylight saving time begins or the time zone offset is increased due to a time
zone rule change), the returned List
will be empty.
Otherwise, the returned List
will have one element.
The default implementation of GetNamedTimeZoneEpochNanoseconds, to be used for ECMAScript
implementations that do not include local political rules for any time zones, performs the
following steps when called:
Assert :
timeZoneIdentifier is "UTC" .
Let epochNanoseconds be GetUTCEpochNanoseconds (year ,
month , day , hour , minute ,
second , millisecond , microsecond ,
nanosecond ).
Return « epochNanoseconds ».
Note
It is required for time zone aware
implementations (and recommended for all others) to use the time zone information of
the IANA Time Zone Database https://www.iana.org/time-zones/ .
1:30 AM on 5 November 2017 in America/New_York is repeated twice, so
GetNamedTimeZoneEpochNanoseconds("America/New_York" , 2017, 11, 5,
1, 30, 0, 0, 0, 0) would return a List of length
2 in which the first element represents 05:30 UTC (corresponding with 01:30 US
Eastern Daylight Time at UTC offset -04:00) and the second element represents 06:30
UTC (corresponding with 01:30 US Eastern Standard Time at UTC offset -05:00).
2:30 AM on 12 March 2017 in America/New_York does not exist, so
GetNamedTimeZoneEpochNanoseconds("America/New_York" , 2017, 3, 12,
2, 30, 0, 0, 0, 0) would return an empty List .
21.4.1.21 GetNamedTimeZoneOffsetNanoseconds (
timeZoneIdentifier , epochNanoseconds )
The implementation-defined abstract
operation GetNamedTimeZoneOffsetNanoseconds takes arguments timeZoneIdentifier (a
String) and epochNanoseconds (a BigInt) and returns an integer .
The returned integer represents the offset from UTC of the named
time zone identified by timeZoneIdentifier , at the instant corresponding with
epochNanoseconds relative to the epoch , both in nanoseconds.
The default implementation of GetNamedTimeZoneOffsetNanoseconds, to be used for ECMAScript
implementations that do not include local political rules for any time zones, performs the
following steps when called:
Assert :
timeZoneIdentifier is "UTC" .
Return 0.
Note
Time zone offset values may be positive or negative.
21.4.1.22 Time Zone Identifier Record
A Time Zone Identifier
Record is a Record
used to describe an available named time zone
identifier and its corresponding primary time zone identifier .
Time Zone Identifier Records have the fields listed in Table 64 .
Table 64: Time Zone Identifier
Record Fields
Note
If [[Identifier]] is a primary time zone
identifier , then [[Identifier]] is
[[PrimaryIdentifier]] .
21.4.1.23 AvailableNamedTimeZoneIdentifiers ( )
The implementation-defined abstract
operation AvailableNamedTimeZoneIdentifiers takes no arguments and returns a List of Time Zone Identifier Records .
Its result describes all available named time zone
identifiers in this implementation, as well as the primary time zone identifier
corresponding to each available named time zone
identifier .
The List is ordered
according to the [[Identifier]] field of each Time Zone Identifier Record .
Time zone aware implementations,
including all implementations that implement the ECMA-402 Internationalization API, must
implement the AvailableNamedTimeZoneIdentifiers abstract operation as specified in the
ECMA-402 specification.
For implementations that are not time zone aware ,
AvailableNamedTimeZoneIdentifiers performs the following steps when called:
If the implementation does not include local political rules for any time zones,
then
Return « the Time Zone
Identifier Record { [[Identifier]] : "UTC" , [[PrimaryIdentifier]] :
"UTC" } ».
Let identifiers be the List of unique
available named time zone
identifiers , sorted according to lexicographic code unit
order .
Let result be a new empty List .
For each element identifier of identifiers , do
Let primary be identifier .
If identifier is a non-primary time
zone identifier in this implementation and
identifier is not "UTC" , then
Set primary to the primary time zone
identifier associated with
identifier .
NOTE: An implementation may need to resolve identifier
iteratively to obtain the primary time zone
identifier .
Let record be the Time Zone Identifier
Record { [[Identifier]] :
identifier , [[PrimaryIdentifier]] :
primary }.
Append record to result .
Assert :
result contains a Time Zone Identifier
Record r such that r .[[Identifier]] is "UTC" and
r .[[PrimaryIdentifier]] is
"UTC" .
Return result .
21.4.1.24 SystemTimeZoneIdentifier ( )
The implementation-defined abstract
operation SystemTimeZoneIdentifier takes no arguments and returns a String.
It returns a String representing the host environment 's current time zone, which
is either a String representing a UTC offset for which IsTimeZoneOffsetString returns
true , or a primary time zone identifier .
It performs the following steps when called:
If the implementation only supports the UTC time zone, return
"UTC" .
Let systemTimeZoneString be the String representing the host
environment 's current time zone, either a primary time zone
identifier or an offset time
zone identifier.
Return systemTimeZoneString .
Note
To ensure the level of functionality that implementations commonly provide in the
methods of the Date object, it is recommended that SystemTimeZoneIdentifier return
an IANA time zone name corresponding to the host environment 's
time zone setting, if such a thing exists.
GetNamedTimeZoneEpochNanoseconds
and GetNamedTimeZoneOffsetNanoseconds
must reflect the local political rules for standard time and daylight saving time in
that time zone, if such rules exist.
For example, if the host environment is a browser on a
system where the user has chosen US Eastern Time as their time zone,
SystemTimeZoneIdentifier returns "America/New_York" .
21.4.1.25 LocalTime ( t )
The abstract operation LocalTime takes argument t (a finite time value ) and returns an
integral
Number .
It converts t from UTC to local time.
The local political rules for standard time and daylight saving time in effect at
t should be used to determine the result in the way specified in this section.
It performs the following steps when called:
Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier ().
If IsTimeZoneOffsetString (systemTimeZoneIdentifier )
is true , then
Let offsetNs be ParseTimeZoneOffsetString (systemTimeZoneIdentifier ).
Else,
Let offsetNs be GetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier ,
ℤ (ℝ (t ) ×
106 )).
Let offsetMs be truncate (offsetNs /
106 ).
Return t + 𝔽 (offsetMs ).
Note 1
If political rules for the local time t are not available within the
implementation, the result is t because SystemTimeZoneIdentifier
returns "UTC" and GetNamedTimeZoneOffsetNanoseconds
returns 0.
Note 2
It is required for time zone aware
implementations (and recommended for all others) to use the time zone information of
the IANA Time Zone Database https://www.iana.org/time-zones/ .
Note 3
Two different input time
values t UTC are converted to the same
local time tlocal at a negative time
zone transition when there are repeated times (e.g. the daylight saving time ends or
the time zone adjustment is decreased.).
LocalTime(UTC (t local ))
is not necessarily always equal to t local . Correspondingly, UTC (LocalTime(t UTC ))
is not necessarily always equal to t UTC .
21.4.1.26 UTC ( t )
The abstract operation UTC takes argument t (a Number) and returns a time value .
It converts t from local time to a UTC time value .
The local political rules for standard time and daylight saving time in effect at
t should be used to determine the result in the way specified in this section.
It performs the following steps when called:
If t is not finite , return NaN .
Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier ().
If IsTimeZoneOffsetString (systemTimeZoneIdentifier )
is true , then
Let offsetNs be ParseTimeZoneOffsetString (systemTimeZoneIdentifier ).
Else,
Let possibleInstants be GetNamedTimeZoneEpochNanoseconds (systemTimeZoneIdentifier ,
ℝ (YearFromTime (t )),
ℝ (MonthFromTime (t ))
+ 1, ℝ (DateFromTime (t )),
ℝ (HourFromTime (t )),
ℝ (MinFromTime (t )),
ℝ (SecFromTime (t )),
ℝ (msFromTime (t )), 0,
0).
NOTE: The following steps ensure that when t represents local
time repeating multiple times at a negative time zone transition (e.g. when
the daylight saving time ends or the time zone offset is decreased due to a
time zone rule change) or skipped local time at a positive time zone
transition (e.g. when the daylight saving time starts or the time zone
offset is increased due to a time zone rule change), t is
interpreted using the time zone offset before the transition.
If possibleInstants is not empty, then
Let disambiguatedInstant be
possibleInstants [0].
Else,
NOTE: t represents a local time skipped at a positive
time zone transition (e.g. due to daylight saving time starting or a
time zone rule change increasing the UTC offset).
Let possibleInstantsBefore be
GetNamedTimeZoneEpochNanoseconds (systemTimeZoneIdentifier ,
ℝ (YearFromTime (tBefore )),
ℝ (MonthFromTime (tBefore ))
+ 1, ℝ (DateFromTime (tBefore )),
ℝ (HourFromTime (tBefore )),
ℝ (MinFromTime (tBefore )),
ℝ (SecFromTime (tBefore )),
ℝ (msFromTime (tBefore )),
0, 0), where tBefore is the largest integral Number <
t for which possibleInstantsBefore is not
empty (i.e., tBefore represents the last local time
before the transition).
Let disambiguatedInstant be the last element of
possibleInstantsBefore .
Let offsetNs be GetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier ,
disambiguatedInstant ).
Let offsetMs be truncate (offsetNs /
106 ).
Return t - 𝔽 (offsetMs ).
Input t is nominally a time value but
may be any Number value.
The algorithm must not limit t to the time value range, so that
inputs corresponding with a boundary of the time value
range can be supported regardless of local UTC offset.
For example, the maximum time value is 8.64 ×
1015 , corresponding with "+275760-09-13T00:00:00Z" .
In an environment where the local time zone offset is ahead of UTC by 1 hour at that
instant, it is represented by the larger input of 8.64 × 1015 + 3.6 ×
106 , corresponding with "+275760-09-13T01:00:00+01:00" .
If political rules for the local time t are not available within the
implementation, the result is t because SystemTimeZoneIdentifier returns
"UTC" and GetNamedTimeZoneOffsetNanoseconds
returns 0.
Note 1
It is required for time zone aware
implementations (and recommended for all others) to use the time zone information of
the IANA Time Zone Database https://www.iana.org/time-zones/ .
1:30 AM on 5 November 2017 in America/New_York is repeated twice (fall backward),
but it must be interpreted as 1:30 AM UTC-04 instead of 1:30 AM UTC-05.
In UTC(TimeClip (MakeDate (MakeDay (2017, 10, 5), MakeTime (1, 30, 0, 0)))), the value of
offsetMs is -4 × msPerHour .
2:30 AM on 12 March 2017 in America/New_York does not exist, but it must be
interpreted as 2:30 AM UTC-05 (equivalent to 3:30 AM UTC-04).
In UTC(TimeClip (MakeDate (MakeDay (2017, 2, 12), MakeTime (2, 30, 0, 0)))), the value of
offsetMs is -5 × msPerHour .
Note 2
UTC(LocalTime (t UTC ))
is not necessarily always equal to t UTC . Correspondingly, LocalTime (UTC(t local ))
is not necessarily always equal to t local .
21.4.1.27 MakeTime ( hour , min ,
sec , ms )
The abstract operation MakeTime takes arguments hour (a Number), min (a
Number), sec (a Number), and ms (a Number) and returns a Number. It
calculates a number of milliseconds. It performs the following steps when called:
If hour is not finite , min is not finite ,
sec is not finite , or ms is not finite , return
NaN .
Let h be 𝔽 (! ToIntegerOrInfinity (hour )).
Let m be 𝔽 (! ToIntegerOrInfinity (min )).
Let s be 𝔽 (! ToIntegerOrInfinity (sec )).
Let milli be 𝔽 (! ToIntegerOrInfinity (ms )).
Return ((h × msPerHour + m × msPerMinute ) + s ×
msPerSecond ) + milli .
Note
The arithmetic in MakeTime is floating-point arithmetic, which is not associative, so
the operations must be performed in the correct order.
21.4.1.28 MakeDay ( year , month ,
date )
The abstract operation MakeDay takes arguments year (a Number), month
(a Number), and date (a Number) and returns a Number. It calculates a number of
days. It performs the following steps when called:
If year is not finite , month is not finite , or
date is not finite , return NaN .
Let y be 𝔽 (! ToIntegerOrInfinity (year )).
Let m be 𝔽 (! ToIntegerOrInfinity (month )).
Let dt be 𝔽 (! ToIntegerOrInfinity (date )).
Let ym be y + 𝔽 (floor (ℝ (m ) / 12)).
If ym is not finite , return NaN .
Let mn be 𝔽 (ℝ (m ) modulo 12).
Find a finite time value
t such that YearFromTime (t ) is
ym , MonthFromTime (t ) is
mn , and DateFromTime (t ) is
1 𝔽 ; but if this is not possible (because some
argument is out of range), return NaN .
Return Day (t ) + dt -
1 𝔽 .
21.4.1.29 MakeDate ( day , time )
The abstract operation MakeDate takes arguments day (a Number) and time
(a Number) and returns a Number. It calculates a number of milliseconds. It performs the
following steps when called:
If day is not finite or time is not finite , return
NaN .
Let tv be day × msPerDay + time .
If tv is not finite , return NaN .
Return tv .
21.4.1.30 MakeFullYear ( year )
The abstract operation MakeFullYear takes argument year (a Number) and returns an
integral
Number or NaN . It returns the full year associated
with the integer
part of year , interpreting any value in the inclusive interval from 0
to 99 as a count of years since the start of 1900. For alignment with the proleptic
Gregorian calendar, "full year" is defined as the signed count of complete years since the
start of year 0 (1 B.C.). It performs the following steps when called:
If year is NaN , return NaN .
Let truncated be ! ToIntegerOrInfinity (year ).
If truncated is in the inclusive interval
from 0 to 99, return 1900 𝔽 + 𝔽 (truncated ).
Return 𝔽 (truncated ).
21.4.1.31 TimeClip ( time )
The abstract operation TimeClip takes argument time (a Number) and returns a
Number. It calculates a number of milliseconds. It performs the following steps when called:
If time is not finite , return NaN .
If abs (ℝ (time )) > 8.64 × 1015 ,
return NaN .
Return 𝔽 (!
ToIntegerOrInfinity (time )).
21.4.1.32 Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of
the ISO 8601 calendar date extended format. The format is as follows:
YYYY-MM-DDTHH:mm:ss.sssZ
Where the elements are as follows:
YYYY
is the year in the proleptic Gregorian calendar as four decimal digits from
0000 to 9999, or as an expanded year of
"+" or "-" followed by six decimal
digits.
-
"-" (hyphen) appears literally twice in the string.
MM
is the month of the year as two decimal digits from 01 (January) to 12
(December).
DD
is the day of the month as two decimal digits from 01 to 31.
T
"T" appears literally in the string, to indicate the
beginning of the time element.
HH
is the number of complete hours that have passed since midnight as two
decimal digits from 00 to 24.
:
":" (colon) appears literally twice in the string.
mm
is the number of complete minutes since the start of the hour as two decimal
digits from 00 to 59.
ss
is the number of complete seconds since the start of the minute as two
decimal digits from 00 to 59.
.
"." (dot) appears literally in the string.
sss
is the number of complete milliseconds since the start of the second as
three decimal digits.
Z
is the UTC offset representation specified as "Z" (for
UTC with no offset) or as either "+" or
"-" followed by a time expression HH:mm (a
subset of the time zone offset
string format for indicating local time ahead of or
behind UTC, respectively)
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above date-only forms
immediately followed by one of the following time forms with an optional UTC offset
representation appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
A string containing out-of-bounds or nonconforming elements is not a valid instance of this
format.
Note 1
As every day both starts and ends with midnight, the two notations 00:00
and 24:00 are available to distinguish the two midnights that can be
associated with one date. This means that the following two notations refer to
exactly the same point in time: 1995-02-04T24:00 and
1995-02-05T00:00. This interpretation of the latter form as "end of a
calendar day" is consistent with ISO 8601, even though that specification reserves
it for describing time intervals and does not permit it within representations of
single points in time.
Note 2
There exists no international standard that specifies abbreviations for civil time
zones like CET, EST, etc. and sometimes the same abbreviation is even used for two
very different time zones. For this reason, both ISO 8601 and this format specify
numeric representations of time zone offsets.
21.4.1.32.1 Expanded Years
Covering the full time value range of
approximately 273,790 years forward or backward from 1 January 1970 (21.4.1.1 ) requires
representing years before 0 or after 9999. ISO 8601 permits expansion of the year
representation, but only by mutual agreement of the partners in information interchange.
In the simplified ECMAScript format, such an expanded year representation shall have 6
digits and is always prefixed with a + or - sign. The year 0 is considered positive and
must be prefixed with a + sign. The representation of the year 0 as -000000 is invalid.
Strings matching the Date Time String Format with
expanded years representing instants in time outside the range of a time value are treated as
unrecognizable by Date.parse and cause that
function to return NaN without falling back to
implementation-specific behaviour or heuristics.
Note
Examples of date-time values with expanded years:
-271821-04-20T00:00:00Z
271822 B.C.
-000001-01-01T00:00:00Z
2 B.C.
+000000-01-01T00:00:00Z
1 B.C.
+000001-01-01T00:00:00Z
1 A.D.
+001970-01-01T00:00:00Z
1970 A.D.
+002009-12-15T00:00:00Z
2009 A.D.
+275760-09-13T00:00:00Z
275760 A.D.
21.4.1.33 Time Zone Offset String Format
ECMAScript defines a string interchange format for UTC offsets, derived from ISO 8601.
The format is described by the following grammar.
Syntax
UTCOffset :::
ASCIISign
Hour
ASCIISign
Hour
HourSubcomponents [+Extended]
ASCIISign
Hour
HourSubcomponents [~Extended]
ASCIISign :::
one of + -
Hour :::
0
DecimalDigit
1
DecimalDigit
20
21
22
23
HourSubcomponents [Extended]
:::
TimeSeparator [?Extended]
MinuteSecond
TimeSeparator [?Extended]
MinuteSecond
TimeSeparator [?Extended]
MinuteSecond
TemporalDecimalFraction opt
TimeSeparator [Extended]
::: [+Extended]
:
[~Extended]
[empty]
MinuteSecond :::
0
DecimalDigit
1
DecimalDigit
2
DecimalDigit
3
DecimalDigit
4
DecimalDigit
5
DecimalDigit
TemporalDecimalFraction
:::
TemporalDecimalSeparator
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
::: one of .
,
21.4.1.33.1 IsTimeZoneOffsetString ( offsetString
)
The abstract operation IsTimeZoneOffsetString takes argument offsetString (a
String) and returns a Boolean. The return value indicates whether
offsetString conforms to the grammar given by UTCOffset . It performs the following steps
when called:
Let parseResult be ParseText (offsetString ,
UTCOffset ).
If parseResult is a List of
errors, return false .
Return true .
21.4.1.33.2 ParseTimeZoneOffsetString (
offsetString )
The abstract operation ParseTimeZoneOffsetString takes argument offsetString
(a String) and returns an integer . The return value is the UTC offset, as a
number of nanoseconds, that corresponds to the String offsetString . It
performs the following steps when called:
Let parseResult be ParseText (offsetString ,
UTCOffset ).
Assert : parseResult is not a
List of
errors.
Assert : parseResult contains a
ASCIISign
Parse Node .
Let parsedSign be the source text
matched by the ASCIISign Parse Node contained within
parseResult .
If parsedSign is the single code point U+002D (HYPHEN-MINUS), then
Let sign be -1.
Else,
Let sign be 1.
NOTE: Applications of StringToNumber below do not
lose precision, since each of the parsed values is guaranteed to be a
sufficiently short string of decimal digits.
Assert : parseResult contains an
Hour Parse Node .
Let parsedHours be the source text
matched by the Hour Parse Node contained within
parseResult .
Let hours be ℝ (StringToNumber (CodePointsToString (parsedHours ))).
If parseResult does not contain a MinuteSecond Parse Node , then
Let minutes be 0.
Else,
Let parsedMinutes be the source
text matched by the first MinuteSecond Parse Node
contained within parseResult .
Let minutes be ℝ (StringToNumber (CodePointsToString (parsedMinutes ))).
If parseResult does not contain two MinuteSecond Parse Nodes , then
Let seconds be 0.
Else,
Let parsedSeconds be the source
text matched by the second MinuteSecond Parse Node
contained within parseResult .
Let seconds be ℝ (StringToNumber (CodePointsToString (parsedSeconds ))).
If parseResult does not contain a TemporalDecimalFraction
Parse Node , then
Let nanoseconds be 0.
Else,
Let parsedFraction be the source
text matched by the TemporalDecimalFraction
Parse Node
contained within parseResult .
Let fraction be the string-concatenation
of CodePointsToString (parsedFraction )
and "000000000" .
Let nanosecondsString be the substring of
fraction from 1 to 10.
Let nanoseconds be ℝ (StringToNumber (nanosecondsString )).
Return sign × (((hours × 60 + minutes ) × 60 +
seconds ) × 109 + nanoseconds ).
21.4.2 The Date Constructor
The Date constructor :
is %Date% .
is the initial value of the "Date" property of the global
object .
creates and initializes a new Date when called as a constructor .
returns a String representing the current time (UTC) when called as a function rather than
as a constructor .
is a function whose behaviour differs based upon the number and types of its arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Date behaviour must include a super call to the Date constructor to
create and initialize the subclass instance with a [[DateValue]]
internal slot.
21.4.2.1 Date ( ...values )
This function performs the following steps when called:
If NewTarget is undefined , then
Let now be the time
value (UTC) identifying the current time.
Return ToDateString (now ).
Let numberOfArgs be the number of elements in values .
If numberOfArgs = 0, then
Let dv be the time
value (UTC) identifying the current time.
Else if numberOfArgs = 1, then
Let value be values [0].
If value is an Object and
value has a [[DateValue]] internal slot,
then
Let tv be value .[[DateValue]] .
Else,
Let v be ? ToPrimitive (value ).
If v is a
String , then
Assert : The next step
never returns an abrupt
completion because v
is
a String .
Let tv be the result of parsing v as a
date, in exactly the same manner as for the
parse method (21.4.3.2 ).
Else,
Let tv be ? ToNumber (v ).
Let dv be TimeClip (tv ).
Else,
Assert : numberOfArgs ≥ 2.
Let y be ? ToNumber (values [0]).
Let m be ? ToNumber (values [1]).
If numberOfArgs > 2, let dt be ? ToNumber (values [2]);
else let dt be 1 𝔽 .
If numberOfArgs > 3, let h be ? ToNumber (values [3]);
else let h be +0 𝔽 .
If numberOfArgs > 4, let min be ? ToNumber (values [4]);
else let min be +0 𝔽 .
If numberOfArgs > 5, let s be ? ToNumber (values [5]);
else let s be +0 𝔽 .
If numberOfArgs > 6, let milli be ? ToNumber (values [6]);
else let milli be +0 𝔽 .
Let yr be MakeFullYear (y ).
Let finalDate be MakeDate (MakeDay (yr ,
m , dt ), MakeTime (h ,
min , s , milli )).
Let dv be TimeClip (UTC (finalDate )).
Let O be ? OrdinaryCreateFromConstructor (NewTarget,
"%Date.prototype%" , « [[DateValue]] »).
Set O .[[DateValue]] to dv .
Return O .
21.4.3 Properties of the Date Constructor
The Date constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has a "length" property whose value is 7 𝔽 .
has the following properties:
21.4.3.1 Date.now ( )
This function returns the time value designating the UTC
date and time of the occurrence of the call to it.
21.4.3.2 Date.parse ( string )
This function applies the ToString operator to its argument. If ToString results
in an abrupt completion
the Completion Record is
immediately returned. Otherwise, this function interprets the resulting String as a date and
time; it returns a Number, the UTC time value
corresponding to the date and time. The String may be interpreted as a local time, a UTC
time, or a time in some other time zone, depending on the contents of the String. The
function first attempts to parse the String according to the format described in Date Time
String Format (21.4.1.32 ), including expanded
years. If the String does not conform to that format the function may fall back to any
implementation-specific heuristics or implementation-specific date formats. Strings that are
unrecognizable or contain out-of-bounds format element values shall cause this function to
return NaN .
If the String conforms to the Date Time String Format ,
substitute values take the place of absent format elements. When the MM or
DD elements are absent, "01" is used. When the
HH, mm, or ss elements are absent,
"00" is used. When the sss element is absent,
"000" is used. When the UTC offset representation is absent, date-only
forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
If x is any Date whose milliseconds amount is zero within a particular
implementation of ECMAScript, then all of the following expressions should produce the same
numeric value in that implementation, if all the properties referenced have their initial
values:
x.valueOf ()
Date .parse (x.toString ())
Date .parse (x.toUTCString ())
Date .parse (x.toISOString ())
However, the expression
Date .parse (x.toLocaleString ())
is not required to produce the same Number value as the preceding three expressions and, in
general, the value produced by this function is implementation-defined
when given any String value that does not conform to the Date Time String Format (21.4.1.32 ) and that could not be
produced in that implementation by the toString or toUTCString
method.
21.4.3.3 Date.prototype
The initial value of Date.prototype is the Date prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
21.4.3.4 Date.UTC ( year [ , month [ ,
date [ , hours [ , minutes [ , seconds [ ,
ms ] ] ] ] ] ] )
This function performs the following steps when called:
Let y be ? ToNumber (year ).
If month is present, let m be ? ToNumber (month ); else let
m be +0 𝔽 .
If date is present, let dt be ? ToNumber (date ); else let
dt be 1 𝔽 .
If hours is present, let h be ? ToNumber (hours ); else let
h be +0 𝔽 .
If minutes is present, let min be ? ToNumber (minutes ); else let
min be +0 𝔽 .
If seconds is present, let s be ? ToNumber (seconds ); else let
s be +0 𝔽 .
If ms is present, let milli be ? ToNumber (ms ); else let
milli be +0 𝔽 .
Let yr be MakeFullYear (y ).
Return TimeClip (MakeDate (MakeDay (yr , m ,
dt ), MakeTime (h , min ,
s , milli ))).
The "length" property of this function is
7 𝔽 .
Note
This function differs from the Date constructor in two ways: it returns a
time value as a
Number, rather than creating a Date, and it interprets the arguments in UTC rather
than as local time.
21.4.4 Properties of the Date Prototype Object
The Date prototype object :
is %Date.prototype% .
is itself an ordinary object .
is not a Date instance and does not have a [[DateValue]] internal
slot.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
Unless explicitly defined otherwise, the methods of the Date prototype object defined below are
not generic and the this value passed to them must be an object that has a
[[DateValue]] internal slot that has been initialized to a time value .
21.4.4.1 Date.prototype.constructor
The initial value of Date.prototype.constructor is %Date% .
21.4.4.2 Date.prototype.getDate ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return DateFromTime (LocalTime (t )).
21.4.4.3 Date.prototype.getDay ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return WeekDay (LocalTime (t )).
21.4.4.4 Date.prototype.getFullYear ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return YearFromTime (LocalTime (t )).
21.4.4.5 Date.prototype.getHours ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return HourFromTime (LocalTime (t )).
21.4.4.6 Date.prototype.getMilliseconds ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return msFromTime (LocalTime (t )).
21.4.4.7 Date.prototype.getMinutes ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return MinFromTime (LocalTime (t )).
21.4.4.8 Date.prototype.getMonth ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return MonthFromTime (LocalTime (t )).
21.4.4.9 Date.prototype.getSeconds ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return SecFromTime (LocalTime (t )).
21.4.4.10 Date.prototype.getTime ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Return dateObject .[[DateValue]] .
21.4.4.11 Date.prototype.getTimezoneOffset ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return (t - LocalTime (t )) / msPerMinute .
21.4.4.12 Date.prototype.getUTCDate ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return DateFromTime (t ).
21.4.4.13 Date.prototype.getUTCDay ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return WeekDay (t ).
21.4.4.14 Date.prototype.getUTCFullYear ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return YearFromTime (t ).
21.4.4.15 Date.prototype.getUTCHours ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return HourFromTime (t ).
21.4.4.16 Date.prototype.getUTCMilliseconds ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return msFromTime (t ).
21.4.4.17 Date.prototype.getUTCMinutes ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return MinFromTime (t ).
21.4.4.18 Date.prototype.getUTCMonth ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return MonthFromTime (t ).
21.4.4.19 Date.prototype.getUTCSeconds ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return SecFromTime (t ).
21.4.4.20 Date.prototype.setDate ( date )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let dt be ? ToNumber (date ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
Let newDate be MakeDate (MakeDay (YearFromTime (t ),
MonthFromTime (t ),
dt ), TimeWithinDay (t )).
Let u be TimeClip (UTC (newDate )).
Set dateObject .[[DateValue]] to u .
Return u .
21.4.4.21 Date.prototype.setFullYear ( year [ ,
month [ , date ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let y be ? ToNumber (year ).
If t is NaN , set t to
+0 𝔽 ; otherwise set t to LocalTime (t ).
If month is not present, let m be MonthFromTime (t );
otherwise let m be ? ToNumber (month ).
If date is not present, let dt be DateFromTime (t );
otherwise let dt be ? ToNumber (date ).
Let newDate be MakeDate (MakeDay (y ,
m , dt ), TimeWithinDay (t )).
Let u be TimeClip (UTC (newDate )).
Set dateObject .[[DateValue]] to u .
Return u .
The "length" property of this method is 3 𝔽 .
Note
If month is not present, this method behaves as if month was
present with the value getMonth(). If date is not present,
it behaves as if date was present with the value getDate().
21.4.4.22 Date.prototype.setHours ( hour [ ,
min [ , sec [ , ms ] ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let h be ? ToNumber (hour ).
If min is present, let m be ? ToNumber (min ).
If sec is present, let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
If min is not present, let m be MinFromTime (t ).
If sec is not present, let s be SecFromTime (t ).
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (h , m ,
s , milli )).
Let u be TimeClip (UTC (date )).
Set dateObject .[[DateValue]] to u .
Return u .
The "length" property of this method is 4 𝔽 .
Note
If min is not present, this method behaves as if min was
present with the value getMinutes(). If sec is not present,
it behaves as if sec was present with the value
getSeconds(). If ms is not present, it behaves as if
ms was present with the value getMilliseconds().
21.4.4.23 Date.prototype.setMilliseconds ( ms )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Set ms to ? ToNumber (ms ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
Let time be MakeTime (HourFromTime (t ),
MinFromTime (t ), SecFromTime (t ),
ms ).
Let u be TimeClip (UTC (MakeDate (Day (t ),
time ))).
Set dateObject .[[DateValue]] to u .
Return u .
21.4.4.24 Date.prototype.setMinutes ( min [ ,
sec [ , ms ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let m be ? ToNumber (min ).
If sec is present, let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
If sec is not present, let s be SecFromTime (t ).
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (HourFromTime (t ),
m , s , milli )).
Let u be TimeClip (UTC (date )).
Set dateObject .[[DateValue]] to u .
Return u .
The "length" property of this method is 3 𝔽 .
Note
If sec is not present, this method behaves as if sec was
present with the value getSeconds(). If ms is not present,
this behaves as if ms was present with the value
getMilliseconds().
21.4.4.25 Date.prototype.setMonth ( month [ ,
date ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let m be ? ToNumber (month ).
If date is present, let dt be ? ToNumber (date ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
If date is not present, let dt be DateFromTime (t ).
Let newDate be MakeDate (MakeDay (YearFromTime (t ),
m , dt ), TimeWithinDay (t )).
Let u be TimeClip (UTC (newDate )).
Set dateObject .[[DateValue]] to u .
Return u .
The "length" property of this method is 2 𝔽 .
Note
If date is not present, this method behaves as if date was
present with the value getDate().
21.4.4.26 Date.prototype.setSeconds ( sec [ ,
ms ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
Set t to LocalTime (t ).
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (HourFromTime (t ),
MinFromTime (t ),
s , milli )).
Let u be TimeClip (UTC (date )).
Set dateObject .[[DateValue]] to u .
Return u .
The "length" property of this method is 2 𝔽 .
Note
If ms is not present, this method behaves as if ms was present
with the value getMilliseconds().
21.4.4.27 Date.prototype.setTime ( time )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be ? ToNumber (time ).
Let v be TimeClip (t ).
Set dateObject .[[DateValue]] to v .
Return v .
21.4.4.28 Date.prototype.setUTCDate ( date )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let dt be ? ToNumber (date ).
If t is NaN , return NaN .
Let newDate be MakeDate (MakeDay (YearFromTime (t ),
MonthFromTime (t ),
dt ), TimeWithinDay (t )).
Let v be TimeClip (newDate ).
Set dateObject .[[DateValue]] to v .
Return v .
21.4.4.29 Date.prototype.setUTCFullYear ( year [ ,
month [ , date ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , set t to
+0 𝔽 .
Let y be ? ToNumber (year ).
If month is not present, let m be MonthFromTime (t );
otherwise let m be ? ToNumber (month ).
If date is not present, let dt be DateFromTime (t );
otherwise let dt be ? ToNumber (date ).
Let newDate be MakeDate (MakeDay (y ,
m , dt ), TimeWithinDay (t )).
Let v be TimeClip (newDate ).
Set dateObject .[[DateValue]] to v .
Return v .
The "length" property of this method is 3 𝔽 .
Note
If month is not present, this method behaves as if month was
present with the value getUTCMonth(). If date is not
present, it behaves as if date was present with the value
getUTCDate().
21.4.4.30 Date.prototype.setUTCHours ( hour [ ,
min [ , sec [ , ms ] ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let h be ? ToNumber (hour ).
If min is present, let m be ? ToNumber (min ).
If sec is present, let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
If min is not present, let m be MinFromTime (t ).
If sec is not present, let s be SecFromTime (t ).
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (h , m ,
s , milli )).
Let v be TimeClip (date ).
Set dateObject .[[DateValue]] to v .
Return v .
The "length" property of this method is 4 𝔽 .
Note
If min is not present, this method behaves as if min was
present with the value getUTCMinutes(). If sec is not
present, it behaves as if sec was present with the value
getUTCSeconds(). If ms is not present, it behaves as if
ms was present with the value getUTCMilliseconds().
21.4.4.31 Date.prototype.setUTCMilliseconds ( ms )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Set ms to ? ToNumber (ms ).
If t is NaN , return NaN .
Let time be MakeTime (HourFromTime (t ),
MinFromTime (t ), SecFromTime (t ),
ms ).
Let v be TimeClip (MakeDate (Day (t ),
time )).
Set dateObject .[[DateValue]] to v .
Return v .
21.4.4.32 Date.prototype.setUTCMinutes ( min [ ,
sec [ , ms ] ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let m be ? ToNumber (min ).
If sec is present, let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
If sec is not present, let s be SecFromTime (t ).
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (HourFromTime (t ),
m , s , milli )).
Let v be TimeClip (date ).
Set dateObject .[[DateValue]] to v .
Return v .
The "length" property of this method is 3 𝔽 .
Note
If sec is not present, this method behaves as if sec was
present with the value getUTCSeconds(). If ms is not
present, it behaves as if ms was present with the value return by
getUTCMilliseconds().
21.4.4.33 Date.prototype.setUTCMonth ( month [ ,
date ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let m be ? ToNumber (month ).
If date is present, let dt be ? ToNumber (date ).
If t is NaN , return NaN .
If date is not present, let dt be DateFromTime (t ).
Let newDate be MakeDate (MakeDay (YearFromTime (t ),
m , dt ), TimeWithinDay (t )).
Let v be TimeClip (newDate ).
Set dateObject .[[DateValue]] to v .
Return v .
The "length" property of this method is 2 𝔽 .
Note
If date is not present, this method behaves as if date was
present with the value getUTCDate().
21.4.4.34 Date.prototype.setUTCSeconds ( sec [ ,
ms ] )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let s be ? ToNumber (sec ).
If ms is present, let milli be ? ToNumber (ms ).
If t is NaN , return NaN .
If ms is not present, let milli be msFromTime (t ).
Let date be MakeDate (Day (t ), MakeTime (HourFromTime (t ),
MinFromTime (t ),
s , milli )).
Let v be TimeClip (date ).
Set dateObject .[[DateValue]] to v .
Return v .
The "length" property of this method is 2 𝔽 .
Note
If ms is not present, this method behaves as if ms was present
with the value getUTCMilliseconds().
21.4.4.35 Date.prototype.toDateString ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let tv be dateObject .[[DateValue]] .
If tv is NaN , return "Invalid
Date" .
Let t be LocalTime (tv ).
Return DateString (t ).
21.4.4.36 Date.prototype.toISOString ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let tv be dateObject .[[DateValue]] .
If tv is NaN , throw a RangeError
exception.
Assert :
tv is an integral Number .
If tv corresponds with a year that cannot be represented in the Date Time String Format ,
throw a RangeError exception.
Return a String representation of tv in the Date Time String Format
on the UTC time scale, including all format elements and the UTC offset
representation "Z" .
21.4.4.37 Date.prototype.toJSON ( key )
This method provides a String representation of a Date for use by JSON.stringify
(25.5.2 ).
It performs the following steps when called:
Let O be ? ToObject (this value).
Let tv be ? ToPrimitive (O ,
number ).
If tv is a
Number and tv is not finite , return
null .
Return ? Invoke (O ,
"toISOString" ).
Note 1
Note 2
This method is intentionally generic; it does not require that its
this value be a Date. Therefore, it can be transferred to other
kinds of objects for use as a method. However, it does require that any such object
have a toISOString method.
21.4.4.38 Date.prototype.toLocaleDateString ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method returns a String value. The contents of the String are implementation-defined , but are
intended to represent the “date” portion of the Date in the current time zone in a
convenient, human-readable form that corresponds to the conventions of the host
environment 's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
21.4.4.39 Date.prototype.toLocaleString ( [ reserved1
[ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method returns a String value. The contents of the String are implementation-defined , but are
intended to represent the Date in the current time zone in a convenient, human-readable form
that corresponds to the conventions of the host environment 's current
locale.
The meaning of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
21.4.4.40 Date.prototype.toLocaleTimeString ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method returns a String value. The contents of the String are implementation-defined , but are
intended to represent the “time” portion of the Date in the current time zone in a
convenient, human-readable form that corresponds to the conventions of the host
environment 's current locale.
The meaning of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
21.4.4.41 Date.prototype.toString ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let tv be dateObject .[[DateValue]] .
Return ToDateString (tv ).
Note 1
For any Date d such that
d.[[DateValue]] is evenly divisible by 1000,
the result of Date.parse(d.toString()) = d.valueOf(). See
21.4.3.2 .
Note 2
This method is not generic; it throws a TypeError exception if its
this value is not a Date. Therefore, it cannot be transferred to
other kinds of objects for use as a method.
21.4.4.41.1 TimeString ( tv )
The abstract operation TimeString takes argument tv (a Number, but not
NaN ) and returns a String. It performs the following steps when
called:
Let hour be ToZeroPaddedDecimalString (ℝ (HourFromTime (tv )),
2).
Let minute be ToZeroPaddedDecimalString (ℝ (MinFromTime (tv )), 2).
Let second be ToZeroPaddedDecimalString (ℝ (SecFromTime (tv )), 2).
Return the string-concatenation of
hour , ":" , minute ,
":" , second , the code unit 0x0020 (SPACE), and
"GMT" .
21.4.4.41.2 DateString ( tv )
The abstract operation DateString takes argument tv (a Number, but not
NaN ) and returns a String. It performs the following steps when
called:
Let weekday be the Name of the entry in Table 65 with the
Number WeekDay (tv ).
Let month be the Name of the entry in Table 66 with the
Number MonthFromTime (tv ).
Let day be ToZeroPaddedDecimalString (ℝ (DateFromTime (tv )),
2).
Let yv be YearFromTime (tv ).
If yv is +0 𝔽 or yv >
+0 𝔽 , let yearSign be the empty String;
otherwise let yearSign be "-" .
Let paddedYear be ToZeroPaddedDecimalString (abs (ℝ (yv )), 4).
Return the string-concatenation of
weekday , the code unit 0x0020 (SPACE), month , the code
unit 0x0020 (SPACE), day , the code unit 0x0020 (SPACE),
yearSign , and paddedYear .
Table 65: Names of days of the week
Number
Name
+0 𝔽
"Sun"
1 𝔽
"Mon"
2 𝔽
"Tue"
3 𝔽
"Wed"
4 𝔽
"Thu"
5 𝔽
"Fri"
6 𝔽
"Sat"
Table 66: Names of months of the year
Number
Name
+0 𝔽
"Jan"
1 𝔽
"Feb"
2 𝔽
"Mar"
3 𝔽
"Apr"
4 𝔽
"May"
5 𝔽
"Jun"
6 𝔽
"Jul"
7 𝔽
"Aug"
8 𝔽
"Sep"
9 𝔽
"Oct"
10 𝔽
"Nov"
11 𝔽
"Dec"
21.4.4.41.3 TimeZoneString ( tv )
The abstract operation TimeZoneString takes argument tv (an integral
Number ) and returns a String. It performs the following steps
when called:
Let systemTimeZoneIdentifier be SystemTimeZoneIdentifier ().
If IsTimeZoneOffsetString (systemTimeZoneIdentifier )
is true , then
Let offsetNs be ParseTimeZoneOffsetString (systemTimeZoneIdentifier ).
Else,
Let offsetNs be GetNamedTimeZoneOffsetNanoseconds (systemTimeZoneIdentifier ,
ℤ (ℝ (tv ) × 106 )).
Let offset be 𝔽 (truncate (offsetNs /
106 )).
If offset is +0 𝔽 or offset
> +0 𝔽 , then
Let offsetSign be "+" .
Let absOffset be offset .
Else,
Let offsetSign be "-" .
Let absOffset be -offset .
Let offsetMin be ToZeroPaddedDecimalString (ℝ (MinFromTime (absOffset )),
2).
Let offsetHour be ToZeroPaddedDecimalString (ℝ (HourFromTime (absOffset )),
2).
Let tzName be an implementation-defined
string that is either the empty String or the string-concatenation of the
code unit 0x0020 (SPACE), the code unit 0x0028 (LEFT PARENTHESIS), an implementation-defined
timezone name, and the code unit 0x0029 (RIGHT PARENTHESIS).
Return the string-concatenation of
offsetSign , offsetHour , offsetMin , and
tzName .
21.4.4.41.4 ToDateString ( tv )
The abstract operation ToDateString takes argument tv (an integral
Number or NaN ) and returns a String. It
performs the following steps when called:
If tv is NaN , return "Invalid
Date" .
Let t be LocalTime (tv ).
Return the string-concatenation of
DateString (t ), the code
unit 0x0020 (SPACE), TimeString (t ), and
TimeZoneString (tv ).
21.4.4.42 Date.prototype.toTimeString ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let tv be dateObject .[[DateValue]] .
If tv is NaN , return "Invalid
Date" .
Let t be LocalTime (tv ).
Return the string-concatenation of
TimeString (t ) and TimeZoneString (tv ).
21.4.4.43 Date.prototype.toUTCString ( )
This method returns a String value representing the instant in time corresponding to the
this value. The format of the String is based upon "HTTP-date" from RFC
7231, generalized to support the full range of times supported by ECMAScript Dates.
It performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let tv be dateObject .[[DateValue]] .
If tv is NaN , return "Invalid
Date" .
Let weekday be the Name of the entry in Table 65 with the Number
WeekDay (tv ).
Let month be the Name of the entry in Table 66 with the Number
MonthFromTime (tv ).
Let day be ToZeroPaddedDecimalString (ℝ (DateFromTime (tv )), 2).
Let yv be YearFromTime (tv ).
If yv is +0 𝔽 or yv >
+0 𝔽 , let yearSign be the empty String;
otherwise let yearSign be "-" .
Let paddedYear be ToZeroPaddedDecimalString (abs (ℝ (yv )), 4).
Return the string-concatenation of
weekday , "," , the code unit 0x0020 (SPACE),
day , the code unit 0x0020 (SPACE), month , the code unit 0x0020
(SPACE), yearSign , paddedYear , the code unit 0x0020 (SPACE),
and TimeString (tv ).
21.4.4.44 Date.prototype.valueOf ( )
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Return dateObject .[[DateValue]] .
21.4.4.45 Date.prototype [ %Symbol.toPrimitive% ] (
hint )
This method is called by ECMAScript language operators to convert a Date to a primitive
value. The allowed values for hint are "default" ,
"number" , and "string" . Dates are unique among
built-in ECMAScript object in that they treat "default" as being
equivalent to "string" , All other built-in ECMAScript objects treat
"default" as being equivalent to "number" .
It performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
If hint is either "string" or
"default" , then
Let tryFirst be string .
Else if hint is "number" , then
Let tryFirst be number .
Else,
Throw a TypeError exception.
Return ? OrdinaryToPrimitive (O ,
tryFirst ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
The value of the "name" property of this method is
"[Symbol.toPrimitive]" .
21.4.5 Properties of Date Instances
Date instances are ordinary objects that inherit properties from the
Date prototype
object . Date instances also have a [[DateValue]]
internal slot. The [[DateValue]] internal slot is the time value represented by this
Date.
22 Text Processing
22.1 String Objects
22.1.1 The String Constructor
The String constructor :
is %String% .
is the initial value of the "String" property of the global
object .
creates and initializes a new String object when called as a constructor .
performs a type conversion when called as a function rather than as a constructor .
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
String behaviour must include a super call to the String constructor to
create and initialize the subclass instance with a [[StringData]]
internal slot.
22.1.1.1 String ( value )
This function performs the following steps when called:
If value is not present, then
Let s be the empty String.
Else,
If NewTarget is undefined and value is a
Symbol , return SymbolDescriptiveString (value ).
Let s be ? ToString (value ).
If NewTarget is undefined , return s .
Return StringCreate (s ,
? GetPrototypeFromConstructor (NewTarget,
"%String.prototype%" )).
22.1.2 Properties of the String Constructor
The String constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
22.1.2.1 String.fromCharCode ( ...codeUnits )
This function may be called with any number of arguments which form the rest parameter
codeUnits .
It performs the following steps when called:
Let result be the empty String.
For each element next of codeUnits , do
Let nextCU be the code unit whose numeric value is ℝ (? ToUint16 (next )).
Set result to the string-concatenation of
result and nextCU .
Return result .
The "length" property of this function is
1 𝔽 .
22.1.2.2 String.fromCodePoint ( ...codePoints )
This function may be called with any number of arguments which form the rest parameter
codePoints .
It performs the following steps when called:
Let result be the empty String.
For each element next of codePoints , do
Let nextCP be ? ToNumber (next ).
If nextCP is not an integral
Number , throw a RangeError
exception.
If ℝ (nextCP ) < 0 or ℝ (nextCP ) > 0x10FFFF, throw a
RangeError exception.
Set result to the string-concatenation of
result and UTF16EncodeCodePoint (ℝ (nextCP )).
Assert : If
codePoints is empty, then result is the empty String.
Return result .
The "length" property of this function is
1 𝔽 .
22.1.2.3 String.prototype
The initial value of String.prototype is the String prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
22.1.2.4 String.raw ( template ,
...substitutions )
This function may be called with a variable number of arguments. The first argument is
template and the remainder of the arguments form the List
substitutions .
It performs the following steps when called:
Let substitutionCount be the number of elements in
substitutions .
Let cooked be ? ToObject (template ).
Let literals be ? ToObject (? Get (cooked ,
"raw" )).
Let literalCount be ? LengthOfArrayLike (literals ).
If literalCount ≤ 0, return the empty String.
Let R be the empty String.
Let nextIndex be 0.
Repeat,
Let nextLiteralVal be ? Get (literals ,
! ToString (𝔽 (nextIndex ))).
Let nextLiteral be ? ToString (nextLiteralVal ).
Set R to the string-concatenation of
R and nextLiteral .
If nextIndex + 1 = literalCount , return R .
If nextIndex < substitutionCount , then
Let nextSubVal be
substitutions [nextIndex ].
Let nextSub be ? ToString (nextSubVal ).
Set R to the string-concatenation
of R and nextSub .
Set nextIndex to nextIndex + 1.
Note
This function is intended for use as a tag function of a Tagged Template (13.3.11 ). When called as such,
the first argument will be a well formed template object and the rest parameter will
contain the substitution values.
22.1.3 Properties of the String Prototype Object
The String prototype object :
is %String.prototype% .
is a String
exotic
object and has the internal methods specified for such objects.
has a [[StringData]] internal slot whose value is the empty String.
has a "length" property whose initial value is
+0 𝔽 and whose attributes are { [[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
Unless explicitly stated otherwise, the methods of the String prototype object defined below are
not generic and the this value passed to them must be either a String value
or an object that has a [[StringData]] internal slot that has been
initialized to a String value.
22.1.3.1 String.prototype.at ( index )
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let len be the length of S .
Let relativeIndex be ? ToIntegerOrInfinity (index ).
If relativeIndex ≥ 0, then
Let k be relativeIndex .
Else,
Let k be len + relativeIndex .
If k < 0 or k ≥ len , return
undefined .
Return the substring of S from k
to k + 1.
22.1.3.2 String.prototype.charAt ( pos )
Note 1
This method returns a single element String containing the code unit at index
pos within the String value resulting from converting this object to a
String. If there is no element at that index, the result is the empty String. The
result is a
String value, not a String object.
If pos is an integral Number , then the result of
x.charAt(pos) is equivalent to the result of
x.substring(pos, pos + 1).
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let position be ? ToIntegerOrInfinity (pos ).
Let size be the length of S .
If position < 0 or position ≥ size , return the
empty String.
Return the substring of S from
position to position + 1.
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.3 String.prototype.charCodeAt ( pos )
Note 1
This method returns a Number (a non-negative integral Number less
than 216 ) that is the numeric value of the code unit at index
pos within the String resulting from converting this object to a String.
If there is no element at that index, the result is NaN .
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let position be ? ToIntegerOrInfinity (pos ).
Let size be the length of S .
If position < 0 or position ≥ size , return
NaN .
Return the Number value for the numeric value
of the code unit at index position within the String S .
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
22.1.3.4 String.prototype.codePointAt ( pos )
Note 1
This method returns a non-negative integral Number less
than or equal to 0x10FFFF 𝔽 that is the numeric value
of the UTF-16 encoded code point (6.1.4 )
starting at the string element at index pos within the String resulting
from converting this object to a String. If there is no element at that index, the
result is undefined . If a valid UTF-16 surrogate
pair does not begin at pos , the result is the code
unit at pos .
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let position be ? ToIntegerOrInfinity (pos ).
Let size be the length of S .
If position < 0 or position ≥ size , return
undefined .
Let cp be CodePointAt (S ,
position ).
Return 𝔽 (cp .[[CodePoint]] ).
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
22.1.3.5 String.prototype.concat ( ...args )
Note 1
When this method is called it returns the String value consisting of the code units
of the this value (converted to a String) followed by the code
units of each of the arguments converted to a String. The result is a String
value, not a String object.
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let R be S .
For each element next of args , do
Let nextString be ? ToString (next ).
Set R to the string-concatenation of
R and nextString .
Return R .
The "length" property of this method is 1 𝔽 .
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
22.1.3.6 String.prototype.constructor
The initial value of String.prototype.constructor is %String% .
22.1.3.7 String.prototype.endsWith ( searchString [ ,
endPosition ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let isRegExp be ? IsRegExp (searchString ).
If isRegExp is true , throw a
TypeError exception.
Let searchStr be ? ToString (searchString ).
Let len be the length of S .
If endPosition is undefined , let pos be
len ; else let pos be ? ToIntegerOrInfinity (endPosition ).
Let end be the result of clamping pos between 0 and
len .
Let searchLength be the length of searchStr .
If searchLength = 0, return true .
Let start be end - searchLength .
If start < 0, return false .
Let substring be the substring of S from
start to end .
If substring is searchStr , return true .
Return false .
Note 1
This method returns true if the sequence of code units of
searchString converted to a String is the same as the corresponding code
units of this object (converted to a String) starting at endPosition -
length(this). Otherwise it returns false .
Note 2
Throwing an exception if the first argument is a RegExp is specified in order to
allow future editions to define extensions that allow such argument values.
Note 3
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.8 String.prototype.includes ( searchString [ ,
position ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let isRegExp be ? IsRegExp (searchString ).
If isRegExp is true , throw a
TypeError exception.
Let searchStr be ? ToString (searchString ).
Let pos be ? ToIntegerOrInfinity (position ).
Assert : If
position is undefined , then pos is 0.
Let len be the length of S .
Let start be the result of clamping pos between 0 and
len .
Let index be StringIndexOf (S ,
searchStr , start ).
If index is not-found , return
false .
Return true .
Note 1
If searchString appears as a substring of the
result of converting this object to a String, at one or more indices that are
greater than or equal to position , this function returns
true ; otherwise, it returns false . If
position is undefined , 0 is assumed, so as to search
all of the String.
Note 2
Throwing an exception if the first argument is a RegExp is specified in order to
allow future editions to define extensions that allow such argument values.
Note 3
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.9 String.prototype.indexOf ( searchString [ ,
position ] )
Note 1
If searchString appears as a substring of the
result of converting this object to a String, at one or more indices that are
greater than or equal to position , then the smallest such index is
returned; otherwise, -1 𝔽 is returned. If
position is undefined ,
+0 𝔽 is assumed, so as to search all of the String.
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let searchStr be ? ToString (searchString ).
Let pos be ? ToIntegerOrInfinity (position ).
Assert : If
position is undefined , then pos is 0.
Let len be the length of S .
Let start be the result of clamping pos between 0 and
len .
Let result be StringIndexOf (S ,
searchStr , start ).
If result is not-found , return
-1 𝔽 .
Return 𝔽 (result ).
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.10 String.prototype.isWellFormed ( )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Return IsStringWellFormedUnicode (S ).
22.1.3.11 String.prototype.lastIndexOf ( searchString
[ , position ] )
Note 1
If searchString appears as a substring of the
result of converting this object to a String at one or more indices that are smaller
than or equal to position , then the greatest such index is returned;
otherwise, -1 𝔽 is returned. If position is
undefined , the length of the String value is assumed, so as to
search all of the String.
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let searchStr be ? ToString (searchString ).
Let numPos be ? ToNumber (position ).
Assert : If
position is undefined , then numPos is
NaN .
If numPos is NaN , let pos be +∞; otherwise
let pos be ! ToIntegerOrInfinity (numPos ).
Let len be the length of S .
Let searchLen be the length of searchStr .
Let start be the result of clamping pos between 0 and
len - searchLen .
Let result be StringLastIndexOf (S ,
searchStr , start ).
If result is not-found , return
-1 𝔽 .
Return 𝔽 (result ).
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.12 String.prototype.localeCompare ( that [ ,
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method returns a Number other than NaN representing the result of an
implementation-defined
locale-sensitive String comparison of the this value (converted to a
String S ) with that (converted to a String thatValue ). The
result is intended to correspond with a sort order of String values according to
conventions of the host environment 's current locale, and will
be negative when S is ordered before thatValue , positive when
S is ordered after thatValue , and zero in all other cases
(representing no relative ordering between S and thatValue ).
Before performing the comparisons, this method performs the following steps to prepare the
Strings:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let thatValue be ? ToString (that ).
The meaning of the optional second and third parameters to this method are defined in the
ECMA-402 specification; implementations that do not include ECMA-402 support must not assign
any other interpretation to those parameter positions.
The actual return values are implementation-defined to permit
encoding additional information in them, but this method, when considered as a method of two
arguments, is required to be a consistent comparator defining a total
ordering on the set of all Strings. This method is also required to recognize and honour
canonical equivalence according to the Unicode Standard, including returning
+0 𝔽 when comparing distinguishable Strings that are
canonically equivalent.
Note 1
This method itself is not directly suitable as an argument to
Array.prototype.sort because the latter requires a function of two
arguments.
Note 2
This method may rely on whatever language- and/or locale-sensitive comparison
functionality is available to the ECMAScript environment from the host
environment , and is intended to compare according to the
conventions of the host environment 's current locale.
However, regardless of comparison capabilities, this method must recognize and
honour canonical equivalence according to the Unicode Standard—for example, the
following comparisons must all return +0 𝔽 :
"\u212B" .localeCompare ("A\u030A" )
"\u2126" .localeCompare ("\u03A9" )
"\u1E69" .localeCompare ("s\u0307\u0323" )
"\u1E0B\u0323" .localeCompare ("\u1E0D\u0307" )
"\u1100\u1161" .localeCompare ("\uAC00" )
For a definition and discussion of canonical equivalence see the Unicode Standard,
chapters 2 and 3, as well as Unicode
Standard Annex #15, Unicode Normalization Forms and Unicode Technical Note #5, Canonical
Equivalence in Applications . Also see Unicode Technical Standard #10, Unicode
Collation Algorithm .
It is recommended that this method should not honour Unicode compatibility
equivalents or compatibility decompositions as defined in the Unicode Standard,
chapter 3, section 3.7.
Note 3
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.13 String.prototype.match ( regexp )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If regexp is neither undefined nor
null , then
Let matcher be ? GetMethod (regexp ,
%Symbol.match% ).
If matcher is not undefined , then
Return ? Call (matcher ,
regexp , « O »).
Let S be ? ToString (O ).
Let rx be ? RegExpCreate (regexp ,
undefined ).
Return ? Invoke (rx , %Symbol.match% , «
S »).
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.14 String.prototype.matchAll ( regexp )
This method performs a regular expression match of the String representing the
this value against regexp and returns an iterator that yields match results.
Each match result is an Array containing the matched portion of the String as the first
element, followed by the portions matched by any capturing groups. If the regular expression
never matches, the returned iterator does not yield any match
results.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If regexp is neither undefined nor
null , then
Let isRegExp be ? IsRegExp (regexp ).
If isRegExp is true , then
Let flags be ? Get (regexp ,
"flags" ).
Perform ? RequireObjectCoercible (flags ).
If ? ToString (flags )
does not contain "g" , throw a
TypeError exception.
Let matcher be ? GetMethod (regexp ,
%Symbol.matchAll% ).
If matcher is not undefined , then
Return ? Call (matcher ,
regexp , « O »).
Let S be ? ToString (O ).
Let rx be ? RegExpCreate (regexp ,
"g" ).
Return ? Invoke (rx , %Symbol.matchAll% , «
S »).
Note 1
This method is intentionally generic, it does not require that
its this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
Note 2
Similarly to String.prototype.split,
String.prototype.matchAll is designed to typically act without mutating its
inputs.
22.1.3.15 String.prototype.normalize ( [ form ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
If form is undefined , let f be
"NFC" .
Else, let f be ? ToString (form ).
If f is not one of "NFC" , "NFD" ,
"NFKC" , or "NFKD" , throw a
RangeError exception.
Let ns be the String value that is the result of normalizing S
into the normalization form named by f as specified in the latest Unicode
Standard, Normalization Forms .
Return ns .
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
22.1.3.16 String.prototype.padEnd ( maxLength [ ,
fillString ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Return ? StringPaddingBuiltinsImpl (O ,
maxLength , fillString , end ).
22.1.3.17 String.prototype.padStart ( maxLength [ ,
fillString ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Return ? StringPaddingBuiltinsImpl (O ,
maxLength , fillString , start ).
22.1.3.17.1 StringPaddingBuiltinsImpl ( O ,
maxLength , fillString , placement )
The abstract operation StringPaddingBuiltinsImpl takes arguments O (an
ECMAScript language value ),
maxLength (an ECMAScript language
value ), fillString (an ECMAScript language value ),
and placement (start or end )
and returns either a normal
completion containing a String or a throw
completion . It performs the following steps when called:
Let S be ? ToString (O ).
Let intMaxLength be ℝ (? ToLength (maxLength )).
Let stringLength be the length of S .
If intMaxLength ≤ stringLength , return S .
If fillString is undefined , set
fillString to the String value consisting solely of the code unit
0x0020 (SPACE).
Else, set fillString to ? ToString (fillString ).
Return StringPad (S ,
intMaxLength , fillString , placement ).
22.1.3.17.2 StringPad ( S , maxLength ,
fillString , placement )
The abstract operation StringPad takes arguments S (a String),
maxLength (a non-negative integer ), fillString (a String), and
placement (start or end ) and
returns a String. It performs the following steps when called:
Let stringLength be the length of S .
If maxLength ≤ stringLength , return S .
If fillString is the empty String, return S .
Let fillLen be maxLength - stringLength .
Let truncatedStringFiller be the String value consisting of repeated
concatenations of fillString truncated to length fillLen .
If placement is start , return the string-concatenation of
truncatedStringFiller and S .
Else, return the string-concatenation of
S and truncatedStringFiller .
Note 1
The argument maxLength will be clamped such that it can be no smaller
than the length of S .
Note 2
The argument fillString defaults to " " (the String
value consisting of the code unit 0x0020 SPACE).
22.1.3.17.3 ToZeroPaddedDecimalString ( n ,
minLength )
The abstract operation ToZeroPaddedDecimalString takes arguments n (a
non-negative integer ) and minLength (a non-negative
integer ) and
returns a String. It performs the following steps when called:
Let S be the String representation of n , formatted as a
decimal number.
Return StringPad (S ,
minLength , "0" , start ).
22.1.3.18 String.prototype.repeat ( count )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let n be ? ToIntegerOrInfinity (count ).
If n < 0 or n = +∞, throw a RangeError
exception.
If n = 0, return the empty String.
Return the String value that is made from n copies of S
appended together.
Note 1
This method creates the String value consisting of the code units of the
this value (converted to String) repeated count times.
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.19 String.prototype.replace ( searchValue ,
replaceValue )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If searchValue is neither undefined nor
null , then
Let replacer be ? GetMethod (searchValue ,
%Symbol.replace% ).
If replacer is not undefined , then
Return ? Call (replacer ,
searchValue , « O ,
replaceValue »).
Let string be ? ToString (O ).
Let searchString be ? ToString (searchValue ).
Let functionalReplace be IsCallable (replaceValue ).
If functionalReplace is false , then
Set replaceValue to ? ToString (replaceValue ).
Let searchLength be the length of searchString .
Let position be StringIndexOf (string ,
searchString , 0).
If position is not-found , return
string .
Let preceding be the substring of string from 0 to
position .
Let following be the substring of string from
position + searchLength .
If functionalReplace is true , then
Let replacement be ? ToString (? Call (replaceValue ,
undefined , « searchString , 𝔽 (position ),
string »)).
Else,
Assert : replaceValue
is
a String .
Let captures be a new empty List .
Let replacement be ! GetSubstitution (searchString ,
string , position , captures ,
undefined , replaceValue ).
Return the string-concatenation of
preceding , replacement , and following .
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.19.1 GetSubstitution ( matched ,
str , position , captures , namedCaptures ,
replacementTemplate )
The abstract operation GetSubstitution takes arguments matched (a String),
str (a String), position (a non-negative integer ), captures (a
List of either
Strings or undefined ), namedCaptures (an Object or
undefined ), and replacementTemplate (a String) and returns
either a normal completion
containing a String or a throw
completion . For the purposes of this abstract operation, a
decimal digit is a code unit in the inclusive interval from
0x0030 (DIGIT ZERO) to 0x0039 (DIGIT NINE). It performs the following steps when called:
Let stringLength be the length of str .
Assert : position ≤
stringLength .
Let result be the empty String.
Let templateRemainder be replacementTemplate .
Repeat, while templateRemainder is not the empty String,
NOTE: The following steps isolate
ref (a prefix of templateRemainder ), determine
refReplacement (its replacement), and then append that
replacement to result .
If templateRemainder starts with "$$" ,
then
Let ref be "$$" .
Let refReplacement be "$" .
Else if templateRemainder starts with
"$`" , then
Let ref be "$`" .
Let refReplacement be the substring of
str from 0 to position .
Else if templateRemainder starts with
"$&" , then
Let ref be "$&" .
Let refReplacement be matched .
Else if templateRemainder starts with "$'"
(0x0024 (DOLLAR SIGN) followed by 0x0027 (APOSTROPHE)), then
Let ref be "$'" .
Let matchLength be the length of matched .
Let tailPos be position +
matchLength .
Let refReplacement be the substring of
str from min (tailPos ,
stringLength ).
NOTE: tailPos can exceed stringLength only
if this abstract operation was invoked by a call to the
intrinsic %Symbol.replace%
method of %RegExp.prototype%
on an object whose "exec" property is not the
intrinsic %RegExp.prototype.exec%.
Else if templateRemainder starts with "$"
followed by 1 or more decimal digits, then
If templateRemainder starts with
"$" followed by 2 or more decimal digits, let
digitCount be 2; otherwise let digitCount
be 1.
Let digits be the substring of
templateRemainder from 1 to 1 +
digitCount .
Let index be ℝ (StringToNumber (digits )).
Assert : 0 ≤
index ≤ 99.
Let captureLen be the number of elements in
captures .
If index > captureLen and
digitCount = 2, then
NOTE: When a two-digit replacement pattern specifies an
index exceeding the count of capturing groups, it is
treated as a one-digit replacement pattern followed by a
literal digit.
Set digitCount to 1.
Set digits to the substring of
digits from 0 to 1.
Set index to ℝ (StringToNumber (digits )).
Let ref be the substring of
templateRemainder from 0 to 1 +
digitCount .
If 1 ≤ index ≤ captureLen , then
Let capture be
captures [index - 1].
If capture is undefined ,
then
Let refReplacement be the empty
String.
Else,
Let refReplacement be
capture .
Else,
Let refReplacement be ref .
Else if templateRemainder starts with
"$<" , then
Let gtPos be StringIndexOf (templateRemainder ,
">" , 0).
If gtPos is not-found or
namedCaptures is undefined , then
Let ref be "$<" .
Let refReplacement be ref .
Else,
Let ref be the substring of
templateRemainder from 0 to gtPos
+ 1.
Let groupName be the substring of
templateRemainder from 2 to gtPos .
Assert :
namedCaptures is an
Object .
Let capture be ? Get (namedCaptures ,
groupName ).
If capture is undefined ,
then
Let refReplacement be the empty
String.
Else,
Let refReplacement be
? ToString (capture ).
Else,
Let ref be the substring of
templateRemainder from 0 to 1.
Let refReplacement be ref .
Let refLength be the length of ref .
Set templateRemainder to the substring of
templateRemainder from refLength .
Set result to the string-concatenation
of result and refReplacement .
Return result .
22.1.3.20 String.prototype.replaceAll ( searchValue ,
replaceValue )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If searchValue is neither undefined nor
null , then
Let isRegExp be ? IsRegExp (searchValue ).
If isRegExp is true , then
Let flags be ? Get (searchValue ,
"flags" ).
Perform ? RequireObjectCoercible (flags ).
If ? ToString (flags )
does not contain "g" , throw a
TypeError exception.
Let replacer be ? GetMethod (searchValue ,
%Symbol.replace% ).
If replacer is not undefined , then
Return ? Call (replacer ,
searchValue , « O ,
replaceValue »).
Let string be ? ToString (O ).
Let searchString be ? ToString (searchValue ).
Let functionalReplace be IsCallable (replaceValue ).
If functionalReplace is false , then
Set replaceValue to ? ToString (replaceValue ).
Let searchLength be the length of searchString .
Let advanceBy be max (1, searchLength ).
Let matchPositions be a new empty List .
Let position be StringIndexOf (string ,
searchString , 0).
Repeat, while position is not not-found ,
Append position to matchPositions .
Set position to StringIndexOf (string ,
searchString , position + advanceBy ).
Let endOfLastMatch be 0.
Let result be the empty String.
For each element p of matchPositions , do
Let preserved be the substring of
string from endOfLastMatch to p .
If functionalReplace is true , then
Let replacement be ? ToString (? Call (replaceValue ,
undefined , « searchString , 𝔽 (p ),
string »)).
Else,
Assert :
replaceValue is a
String .
Let captures be a new empty List .
Let replacement be ! GetSubstitution (searchString ,
string , p , captures ,
undefined , replaceValue ).
Set result to the string-concatenation of
result , preserved , and replacement .
Set endOfLastMatch to p + searchLength .
If endOfLastMatch < the length of string , then
Set result to the string-concatenation of
result and the substring of string from
endOfLastMatch .
Return result .
22.1.3.21 String.prototype.search ( regexp )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If regexp is neither undefined nor
null , then
Let searcher be ? GetMethod (regexp ,
%Symbol.search% ).
If searcher is not undefined , then
Return ? Call (searcher ,
regexp , « O »).
Let string be ? ToString (O ).
Let rx be ? RegExpCreate (regexp ,
undefined ).
Return ? Invoke (rx , %Symbol.search% , «
string »).
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.22 String.prototype.slice ( start ,
end )
This method returns a substring of the result of converting this
object to a String, starting from index start and running to, but not including,
index end (or through the end of the String if end is
undefined ). If start is negative, it is treated as sourceLength + start where
sourceLength is the length of the String. If end is negative, it is
treated as sourceLength + end where
sourceLength is the length of the String. The result is a String value,
not a String object.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let len be the length of S .
Let intStart be ? ToIntegerOrInfinity (start ).
If intStart = -∞, let from be 0.
Else if intStart < 0, let from be max (len +
intStart , 0).
Else, let from be min (intStart , len ).
If end is undefined , let intEnd be
len ; else let intEnd be ? ToIntegerOrInfinity (end ).
If intEnd = -∞, let to be 0.
Else if intEnd < 0, let to be max (len +
intEnd , 0).
Else, let to be min (intEnd , len ).
If from ≥ to , return the empty String.
Return the substring of S from
from to to .
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
22.1.3.23 String.prototype.split ( separator ,
limit )
This method returns an Array into which substrings of the result of converting this object to
a String have been stored. The substrings are determined by searching from left to right for
occurrences of separator ; these occurrences are not part of any String in the
returned array, but serve to divide up the String value. The value of separator
may be a String of any length or it may be an object, such as a RegExp, that has a %Symbol.split% method.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
If separator is neither undefined nor
null , then
Let splitter be ? GetMethod (separator ,
%Symbol.split% ).
If splitter is not undefined , then
Return ? Call (splitter ,
separator , « O , limit »).
Let S be ? ToString (O ).
If limit is undefined , let lim be
232 - 1; else let lim be ℝ (? ToUint32 (limit )).
Let R be ? ToString (separator ).
If lim = 0, then
Return CreateArrayFromList (« »).
If separator is undefined , then
Return CreateArrayFromList («
S »).
Let separatorLength be the length of R .
If separatorLength = 0, then
Let strLen be the length of S .
Let outLen be the result of clamping
lim between 0 and strLen .
Let head be the substring of S from 0 to
outLen .
Let codeUnits be a List
consisting of the sequence of code units that are the elements of
head .
Return CreateArrayFromList (codeUnits ).
If S is the empty String, return CreateArrayFromList («
S »).
Let substrings be a new empty List .
Let i be 0.
Let j be StringIndexOf (S ,
R , 0).
Repeat, while j is not not-found ,
Let T be the substring of S from
i to j .
Append T to substrings .
If the number of elements in substrings is lim , return
CreateArrayFromList (substrings ).
Set i to j + separatorLength .
Set j to StringIndexOf (S ,
R , i ).
Let T be the substring of S from
i .
Append T to substrings .
Return CreateArrayFromList (substrings ).
Note 1
The value of separator may be an empty String. In this case,
separator does not match the empty substring
at the beginning or end of the input String, nor does it match the empty
substring at the end of the previous separator match. If
separator is the empty String, the String is split up into individual
code unit elements; the length of the result array equals the length of the String,
and each substring contains one code unit.
If the this value is (or converts to) the empty String, the result
depends on whether separator can match the empty String. If it can, the
result array contains no elements. Otherwise, the result array contains one element,
which is the empty String.
If separator is undefined , then the result array
contains just one String, which is the this value (converted to a
String). If limit is not undefined , then the output
array is truncated so that it contains no more than limit elements.
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.24 String.prototype.startsWith ( searchString
[ , position ] )
This method performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let isRegExp be ? IsRegExp (searchString ).
If isRegExp is true , throw a
TypeError exception.
Let searchStr be ? ToString (searchString ).
Let len be the length of S .
If position is undefined , let pos be 0;
else let pos be ? ToIntegerOrInfinity (position ).
Let start be the result of clamping pos between 0 and
len .
Let searchLength be the length of searchStr .
If searchLength = 0, return true .
Let end be start + searchLength .
If end > len , return false .
Let substring be the substring of S from
start to end .
If substring is searchStr , return true .
Return false .
Note 1
This method returns true if the sequence of code units of
searchString converted to a String is the same as the corresponding code
units of this object (converted to a String) starting at index position .
Otherwise it returns false .
Note 2
Throwing an exception if the first argument is a RegExp is specified in order to
allow future editions to define extensions that allow such argument values.
Note 3
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.25 String.prototype.substring ( start ,
end )
This method returns a substring of the result of converting this
object to a String, starting from index start and running to, but not including,
index end of the String (or through the end of the String if end is
undefined ). The result is a String value,
not a String object.
If either argument is NaN or negative, it is replaced with zero; if either
argument is strictly greater than the length of the String, it is replaced with the length
of the String.
If start is strictly greater than end , they are swapped.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let len be the length of S .
Let intStart be ? ToIntegerOrInfinity (start ).
If end is undefined , let intEnd be
len ; else let intEnd be ? ToIntegerOrInfinity (end ).
Let finalStart be the result of clamping intStart
between 0 and len .
Let finalEnd be the result of clamping intEnd
between 0 and len .
Let from be min (finalStart ,
finalEnd ).
Let to be max (finalStart ,
finalEnd ).
Return the substring of S from
from to to .
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.26 String.prototype.toLocaleLowerCase ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It works exactly the same as toLowerCase except that it is intended to yield a
locale-sensitive result corresponding with conventions of the host
environment 's current locale. There will only be a difference in the
few cases (such as Turkish) where the rules for that language conflict with the regular
Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.27 String.prototype.toLocaleUpperCase ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used:
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It works exactly the same as toUpperCase except that it is intended to yield a
locale-sensitive result corresponding with conventions of the host
environment 's current locale. There will only be a difference in the
few cases (such as Turkish) where the rules for that language conflict with the regular
Unicode case mappings.
The meaning of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.28 String.prototype.toLowerCase ( )
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let sText be StringToCodePoints (S ).
Let lowerText be toLowercase(sText ), according to the Unicode
Default Case Conversion algorithm.
Let L be CodePointsToString (lowerText ).
Return L .
The result must be derived according to the locale-insensitive case mappings in the Unicode
Character Database (this explicitly includes not only the file UnicodeData.txt ,
but also all locale-insensitive mappings in the file SpecialCasing.txt
that accompanies it).
Note 1
The case mapping of some code points may produce multiple code points. In this case
the result String may not be the same length as the source String. Because both
toUpperCase and toLowerCase have context-sensitive
behaviour, the methods are not symmetrical. In other words,
s.toUpperCase().toLowerCase() is not necessarily equal to
s.toLowerCase().
Note 2
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.29 String.prototype.toString ( )
This method performs the following steps when called:
Return ? ThisStringValue (this
value).
Note
For a String object, this method happens to return the same thing as the
valueOf method.
22.1.3.30 String.prototype.toUpperCase ( )
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It behaves in exactly the same way as String.prototype.toLowerCase, except that
the String is mapped using the toUppercase algorithm of the Unicode Default Case Conversion.
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.31 String.prototype.toWellFormed ( )
This method returns a String representation of this object with all leading
surrogates and trailing surrogates that
are not part of a surrogate pair replaced with U+FFFD
(REPLACEMENT CHARACTER).
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let strLen be the length of S .
Let k be 0.
Let result be the empty String.
Repeat, while k < strLen ,
Let cp be CodePointAt (S ,
k ).
If cp .[[IsUnpairedSurrogate]] is
true , then
Set result to the string-concatenation
of result and 0xFFFD (REPLACEMENT CHARACTER).
Else,
Set result to the string-concatenation
of result and UTF16EncodeCodePoint (cp .[[CodePoint]] ).
Set k to k + cp .[[CodeUnitCount]] .
Return result .
22.1.3.32 String.prototype.trim ( )
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It performs the following steps when called:
Let S be the this value.
Return ? TrimString (S ,
start+end ).
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.32.1 TrimString ( string , where
)
The abstract operation TrimString takes arguments string (an ECMAScript language value )
and where (start , end , or
start+end ) and returns either a normal completion
containing a String or a throw
completion . It interprets string as a sequence of
UTF-16 encoded code points, as described in 6.1.4 . It
performs the following steps when called:
Let str be ? RequireObjectCoercible (string ).
Let S be ? ToString (str ).
If where is start , then
Let T be the String value that is a copy of S with
leading white space removed.
Else if where is end , then
Let T be the String value that is a copy of S with
trailing white space removed.
Else,
Assert : where is
start+end .
Let T be the String value that is a copy of S with
both leading and trailing white space removed.
Return T .
The definition of white space is the union of WhiteSpace and LineTerminator . When determining
whether a Unicode code point is in Unicode general category “Space_Separator” (“Zs”),
code unit sequences are interpreted as UTF-16 encoded code point sequences as specified
in 6.1.4 .
22.1.3.33 String.prototype.trimEnd ( )
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It performs the following steps when called:
Let S be the this value.
Return ? TrimString (S ,
end ).
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.34 String.prototype.trimStart ( )
This method interprets a String value as a sequence of UTF-16 encoded code points, as
described in 6.1.4 .
It performs the following steps when called:
Let S be the this value.
Return ? TrimString (S ,
start ).
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore, it can be transferred
to other kinds of objects for use as a method.
22.1.3.35 String.prototype.valueOf ( )
This method performs the following steps when called:
Return ? ThisStringValue (this
value).
22.1.3.35.1 ThisStringValue ( value )
The abstract operation ThisStringValue takes argument value (an ECMAScript language value )
and returns either a normal
completion containing a String or a throw
completion . It performs the following steps when called:
If value is a
String , return value .
If value is an Object and value
has a [[StringData]] internal slot, then
Let s be value .[[StringData]] .
Assert : s is a
String .
Return s .
Throw a TypeError exception.
22.1.3.36 String.prototype [ %Symbol.iterator% ] ( )
This method returns an iterator object that iterates over the
code points of a String value, returning each code point as a String value.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let s be ? ToString (O ).
Let closure be a new Abstract Closure
with no parameters that captures s and performs the following steps when
called:
Let len be the length of s .
Let position be 0.
Repeat, while position < len ,
Let cp be CodePointAt (s ,
position ).
Let nextIndex be position + cp .[[CodeUnitCount]] .
Let resultString be the substring of
s from position to nextIndex .
Set position to nextIndex .
Perform ? GeneratorYield (CreateIteratorResultObject (resultString ,
false )).
Return NormalCompletion (unused ).
Return CreateIteratorFromClosure (closure ,
"%StringIteratorPrototype%" , %StringIteratorPrototype% ).
The value of the "name" property of this method is
"[Symbol.iterator]" .
22.1.4 Properties of String Instances
String instances are String exotic objects and have the internal
methods specified for such objects. String instances inherit properties from the String prototype
object . String instances also have a [[StringData]] internal slot. The [[StringData]] internal slot is the String value represented by this
String object.
String instances have a "length" property, and a set of enumerable properties
with integer-indexed names.
22.1.4.1 length
The number of elements in the String value represented by this String object.
Once a String object is initialized, this property is unchanging. It has the attributes {
[[Writable]] : false , [[Enumerable]] : false , [[Configurable]] : false }.
22.1.5 String Iterator Objects
A String Iterator is an object that represents a specific iteration over
some specific String instance object. There is not a named constructor for String Iterator
objects. Instead, String Iterator objects are created by calling certain methods of String
instance objects.
22.1.5.1 The %StringIteratorPrototype% Object
The %StringIteratorPrototype% object:
22.1.5.1.1 %StringIteratorPrototype%.next ( )
Return ? GeneratorResume (this
value, empty ,
"%StringIteratorPrototype%" ).
22.1.5.1.2 %StringIteratorPrototype% [ %Symbol.toStringTag%
]
The initial value of the %Symbol.toStringTag% property is
the String value "String Iterator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
22.2 RegExp (Regular Expression) Objects
A RegExp object contains a regular expression and the associated flags.
Note
The form and functionality of regular expressions is modelled after the regular expression
facility in the Perl 5 programming language.
22.2.1 Patterns
The RegExp constructor applies the following grammar to the
input pattern String. An error occurs if the grammar cannot interpret the String as an expansion
of Pattern .
Syntax
Pattern [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Disjunction [UnicodeMode,
UnicodeSetsMode, NamedCaptureGroups]
::
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
|
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Alternative [UnicodeMode,
UnicodeSetsMode, NamedCaptureGroups]
::
[empty]
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Term [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Term [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
Assertion [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Atom [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Atom [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Quantifier
Assertion [UnicodeMode,
UnicodeSetsMode, NamedCaptureGroups]
::
^
$
\b
\B
(?=
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?!
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?<=
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?<!
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
Quantifier ::
QuantifierPrefix
QuantifierPrefix
?
QuantifierPrefix ::
*
+
?
{
DecimalDigits [~Sep]
}
{
DecimalDigits [~Sep]
,}
{
DecimalDigits [~Sep]
,
DecimalDigits [~Sep]
}
Atom [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
PatternCharacter
.
\
AtomEscape [?UnicodeMode,
?NamedCaptureGroups]
CharacterClass [?UnicodeMode,
?UnicodeSetsMode]
(
GroupSpecifier [?UnicodeMode] opt
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
:
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
RegularExpressionModifiers
::
[empty]
RegularExpressionModifiers
RegularExpressionModifier
RegularExpressionModifier
:: one of i
m s
SyntaxCharacter ::
one of ^ $ \
. * + ? (
) [ ] { }
|
PatternCharacter ::
SourceCharacter
but not SyntaxCharacter
AtomEscape [UnicodeMode,
NamedCaptureGroups] ::
DecimalEscape
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode]
[+NamedCaptureGroups]
k
GroupName [?UnicodeMode]
CharacterEscape [UnicodeMode]
::
ControlEscape
c
AsciiLetter
0
[lookahead ∉ DecimalDigit ]
HexEscapeSequence
RegExpUnicodeEscapeSequence [?UnicodeMode]
IdentityEscape [?UnicodeMode]
ControlEscape ::
one of f n r
t v
GroupSpecifier [UnicodeMode]
::
?
GroupName [?UnicodeMode]
GroupName [UnicodeMode]
::
<
RegExpIdentifierName [?UnicodeMode]
>
RegExpIdentifierName [UnicodeMode]
::
RegExpIdentifierStart [?UnicodeMode]
RegExpIdentifierName [?UnicodeMode]
RegExpIdentifierPart [?UnicodeMode]
RegExpIdentifierStart [UnicodeMode]
::
IdentifierStartChar
\
RegExpUnicodeEscapeSequence [+UnicodeMode]
[~UnicodeMode]
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpIdentifierPart [UnicodeMode]
::
IdentifierPartChar
\
RegExpUnicodeEscapeSequence [+UnicodeMode]
[~UnicodeMode]
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpUnicodeEscapeSequence [UnicodeMode]
:: [+UnicodeMode]
u
HexLeadSurrogate
\u
HexTrailSurrogate
[+UnicodeMode]
u
HexLeadSurrogate
[+UnicodeMode]
u
HexTrailSurrogate
[+UnicodeMode]
u
HexNonSurrogate
[~UnicodeMode]
u
Hex4Digits
[+UnicodeMode]
u{
CodePoint
}
UnicodeLeadSurrogate
::
any Unicode code point in the inclusive interval from U+D800 to
U+DBFF
UnicodeTrailSurrogate
::
any Unicode code point in the inclusive interval from U+DC00 to
U+DFFF
Each \u HexTrailSurrogate for which the choice of
associated u HexLeadSurrogate is ambiguous shall be
associated with the nearest possible u HexLeadSurrogate that would otherwise have no
corresponding \u HexTrailSurrogate .
HexLeadSurrogate ::
Hex4Digits
but only if the MV of Hex4Digits is in the inclusive interval from 0xD800 to
0xDBFF
HexNonSurrogate ::
Hex4Digits
but only if the MV of Hex4Digits is not in the inclusive interval from 0xD800 to
0xDFFF
IdentityEscape [UnicodeMode]
:: [+UnicodeMode]
SyntaxCharacter
[+UnicodeMode]
/
[~UnicodeMode]
SourceCharacter
but not UnicodeIDContinue
DecimalEscape ::
NonZeroDigit
DecimalDigits [~Sep] opt
[lookahead ∉ DecimalDigit ]
CharacterClassEscape [UnicodeMode]
::
d
D
s
S
w
W
[+UnicodeMode]
p{
UnicodePropertyValueExpression
}
[+UnicodeMode]
P{
UnicodePropertyValueExpression
}
UnicodePropertyValueExpression
::
UnicodePropertyName
=
UnicodePropertyValue
LoneUnicodePropertyNameOrValue
UnicodePropertyName
::
UnicodePropertyNameCharacters
UnicodePropertyNameCharacters
::
UnicodePropertyNameCharacter
UnicodePropertyNameCharacters opt
UnicodePropertyValue
::
UnicodePropertyValueCharacters
LoneUnicodePropertyNameOrValue
::
UnicodePropertyValueCharacters
UnicodePropertyValueCharacters
::
UnicodePropertyValueCharacter
UnicodePropertyValueCharacters opt
UnicodePropertyValueCharacter
::
UnicodePropertyNameCharacter
DecimalDigit
UnicodePropertyNameCharacter
::
AsciiLetter
_
CharacterClass [UnicodeMode,
UnicodeSetsMode] ::
[
[lookahead ≠ ^ ]
ClassContents [?UnicodeMode,
?UnicodeSetsMode]
]
[^
ClassContents [?UnicodeMode,
?UnicodeSetsMode]
]
ClassContents [UnicodeMode,
UnicodeSetsMode] ::
[empty]
[~UnicodeSetsMode]
NonemptyClassRanges [?UnicodeMode]
[+UnicodeSetsMode]
ClassSetExpression
NonemptyClassRanges [UnicodeMode]
::
ClassAtom [?UnicodeMode]
ClassAtom [?UnicodeMode]
NonemptyClassRangesNoDash [?UnicodeMode]
ClassAtom [?UnicodeMode]
-
ClassAtom [?UnicodeMode]
ClassContents [?UnicodeMode,
~UnicodeSetsMode]
NonemptyClassRangesNoDash [UnicodeMode]
::
ClassAtom [?UnicodeMode]
ClassAtomNoDash [?UnicodeMode]
NonemptyClassRangesNoDash [?UnicodeMode]
ClassAtomNoDash [?UnicodeMode]
-
ClassAtom [?UnicodeMode]
ClassContents [?UnicodeMode,
~UnicodeSetsMode]
ClassAtom [UnicodeMode]
::
-
ClassAtomNoDash [?UnicodeMode]
ClassAtomNoDash [UnicodeMode]
::
SourceCharacter
but not one of \ or ] or
-
\
ClassEscape [?UnicodeMode]
ClassEscape [UnicodeMode]
::
b
[+UnicodeMode]
-
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode]
ClassSetExpression
::
ClassUnion
ClassIntersection
ClassSubtraction
ClassUnion ::
ClassSetRange
ClassUnion opt
ClassSetOperand
ClassUnion opt
ClassIntersection
::
ClassSetOperand
&&
[lookahead ≠ & ]
ClassSetOperand
ClassIntersection
&&
[lookahead ≠ & ]
ClassSetOperand
ClassSubtraction ::
ClassSetOperand
--
ClassSetOperand
ClassSubtraction
--
ClassSetOperand
ClassSetRange ::
ClassSetCharacter
-
ClassSetCharacter
ClassSetOperand ::
NestedClass
ClassStringDisjunction
ClassSetCharacter
NestedClass ::
[
[lookahead ≠ ^ ]
ClassContents [+UnicodeMode,
+UnicodeSetsMode]
]
[^
ClassContents [+UnicodeMode,
+UnicodeSetsMode]
]
\
CharacterClassEscape [+UnicodeMode]
Note 1
The first two lines here are equivalent to CharacterClass.
ClassStringDisjunction
::
\q{
ClassStringDisjunctionContents
}
ClassStringDisjunctionContents
::
ClassString
ClassString
|
ClassStringDisjunctionContents
ClassString ::
[empty]
NonEmptyClassString
NonEmptyClassString
::
ClassSetCharacter
NonEmptyClassString opt
ClassSetCharacter
::
[lookahead ∉ ClassSetReservedDoublePunctuator ]
SourceCharacter
but not ClassSetSyntaxCharacter
\
CharacterEscape [+UnicodeMode]
\
ClassSetReservedPunctuator
\b
ClassSetReservedDoublePunctuator
:: one of &&
!! ## $$ %%
** ++ ,, ..
:: ;; << ==
>> ?? @@ ^^
`` ~~
ClassSetSyntaxCharacter
:: one of (
) [ ] { }
/ - \ |
ClassSetReservedPunctuator
:: one of &
- ! # % ,
: ; < =
> @ ` ~
Note 2
A number of productions in this section are given alternative definitions in section
B.1.2 .
22.2.1.1 Static Semantics: Early Errors
Note
This section is amended in B.1.2.1 .
Pattern :: Disjunction
QuantifierPrefix
::
{
DecimalDigits
,
DecimalDigits
}
Atom ::
(?
RegularExpressionModifiers
:
Disjunction
)
Atom ::
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction
)
AtomEscape ::
k
GroupName
AtomEscape ::
DecimalEscape
NonemptyClassRanges
::
ClassAtom
-
ClassAtom
ClassContents
NonemptyClassRangesNoDash
::
ClassAtomNoDash
-
ClassAtom
ClassContents
RegExpIdentifierStart
::
\
RegExpUnicodeEscapeSequence
RegExpIdentifierStart
::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpIdentifierPart
::
\
RegExpUnicodeEscapeSequence
RegExpIdentifierPart
::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
UnicodePropertyValueExpression
::
UnicodePropertyName
=
UnicodePropertyValue
UnicodePropertyValueExpression
:: LoneUnicodePropertyNameOrValue
CharacterClassEscape
::
P{
UnicodePropertyValueExpression
}
CharacterClass ::
[^
ClassContents
]
NestedClass ::
[^
ClassContents
]
ClassSetRange ::
ClassSetCharacter
-
ClassSetCharacter
22.2.1.2 Static Semantics: CountLeftCapturingParensWithin (
node )
The abstract operation CountLeftCapturingParensWithin takes argument node (a
Parse Node ) and returns a non-negative
integer . It
returns the number of left-capturing parentheses in node . A left-capturing parenthesis is
any ( pattern character that is matched by the ( terminal of the
Atom ::
(
GroupSpecifier opt
Disjunction
)
production.
Note
This section is amended in B.1.2.2 .
It performs the following steps when called:
Assert :
node is an instance of a production in the RegExp Pattern grammar .
Return the number of
Atom ::
(
GroupSpecifier opt
Disjunction
)
Parse Nodes contained within
node .
22.2.1.3 Static Semantics: CountLeftCapturingParensBefore (
node )
The abstract operation CountLeftCapturingParensBefore takes argument node (a
Parse Node ) and returns a non-negative
integer . It
returns the number of left-capturing
parentheses within the enclosing pattern that occur to the left of
node .
Note
This section is amended in B.1.2.2 .
It performs the following steps when called:
Assert :
node is an instance of a production in the RegExp Pattern grammar .
Let pattern be the Pattern containing node .
Return the number of
Atom ::
(
GroupSpecifier opt
Disjunction
)
Parse Nodes contained within
pattern that either occur before node or contain
node .
22.2.1.4 Static Semantics: MightBothParticipate ( x ,
y )
The abstract operation MightBothParticipate takes arguments x (a Parse
Node ) and y (a Parse Node ) and returns
a Boolean. It performs the following steps when called:
Assert :
x and y have the same enclosing Pattern .
If the enclosing Pattern contains a
Disjunction
::
Alternative
|
Disjunction
Parse Node such that either
x is contained within the Alternative and y is
contained within the derived Disjunction , or x is
contained within the derived Disjunction and y is
contained within the Alternative , return
false .
Return true .
22.2.1.5 Static Semantics: CapturingGroupNumber
The syntax-directed
operation CapturingGroupNumber takes no arguments and returns a
positive integer .
Note
This section is amended in B.1.2.1 .
It is defined piecewise over the following productions:
DecimalEscape ::
NonZeroDigit
Return the MV of NonZeroDigit .
DecimalEscape ::
NonZeroDigit
DecimalDigits
Let n be the number of code points in DecimalDigits .
Return (the MV of NonZeroDigit ×
10n plus the MV of DecimalDigits ).
The definitions of “the MV of NonZeroDigit ” and “the MV of DecimalDigits ” are in
12.9.3 .
22.2.1.6 Static Semantics: IsCharacterClass
The syntax-directed
operation IsCharacterClass takes no arguments and returns a Boolean.
Note
This section is amended in B.1.2.3 .
It is defined piecewise over the following productions:
ClassAtom ::
-
ClassAtomNoDash
::
SourceCharacter
but not one of \ or ] or
-
ClassEscape ::
b
-
CharacterEscape
Return false .
ClassEscape ::
CharacterClassEscape
Return true .
22.2.1.7 Static Semantics: CharacterValue
The syntax-directed
operation CharacterValue takes no arguments and returns a
non-negative integer .
Note 1
This section is amended in B.1.2.4 .
It is defined piecewise over the following productions:
ClassAtom :: -
Return the numeric value of U+002D (HYPHEN-MINUS).
ClassAtomNoDash
:: SourceCharacter
but not one of \ or ] or
-
Let ch be the code point matched by SourceCharacter .
Return the numeric value of ch .
ClassEscape ::
b
Return the numeric value of U+0008 (BACKSPACE).
ClassEscape ::
Return the numeric value of U+002D (HYPHEN-MINUS).
CharacterEscape
:: ControlEscape
Return the numeric value according to Table 67 .
Table 67: ControlEscape Code Point Values
ControlEscape
Numeric Value
Code Point
Unicode Name
Symbol
t
9
U+0009
CHARACTER TABULATION
<HT>
n
10
U+000A
LINE FEED (LF)
<LF>
v
11
U+000B
LINE TABULATION
<VT>
f
12
U+000C
FORM FEED (FF)
<FF>
r
13
U+000D
CARRIAGE RETURN (CR)
<CR>
CharacterEscape
::
c
AsciiLetter
Let ch be the code point matched by AsciiLetter .
Let i be the numeric value of ch .
Return the remainder of dividing i by 32.
CharacterEscape
::
0
[lookahead ∉ DecimalDigit ]
Return the numeric value of U+0000 (NULL).
Note 2
\0 represents the <NUL> character and cannot be followed by a
decimal digit.
CharacterEscape
:: HexEscapeSequence
Return the MV of HexEscapeSequence .
RegExpUnicodeEscapeSequence
::
u
HexLeadSurrogate
\u
HexTrailSurrogate
Let lead be the CharacterValue
of HexLeadSurrogate .
Let trail be the CharacterValue
of HexTrailSurrogate .
Let cp be UTF16SurrogatePairToCodePoint (lead ,
trail ).
Return the numeric value of cp .
RegExpUnicodeEscapeSequence
::
u
Hex4Digits
Return the MV of Hex4Digits .
RegExpUnicodeEscapeSequence
::
u{
CodePoint
}
Return the MV of CodePoint .
HexLeadSurrogate
:: Hex4Digits
HexTrailSurrogate
:: Hex4Digits
HexNonSurrogate
:: Hex4Digits
Return the MV of Hex4Digits .
CharacterEscape
:: IdentityEscape
Let ch be the code point matched by IdentityEscape .
Return the numeric value of ch .
ClassSetCharacter
:: SourceCharacter
but not ClassSetSyntaxCharacter
Let ch be the code point matched by SourceCharacter .
Return the numeric value of ch .
ClassSetCharacter
::
\
ClassSetReservedPunctuator
Let ch be the code point matched by ClassSetReservedPunctuator .
Return the numeric value of ch .
ClassSetCharacter
:: \b
Return the numeric value of U+0008 (BACKSPACE).
22.2.1.8 Static Semantics: MayContainStrings
The syntax-directed
operation MayContainStrings takes no arguments and returns a Boolean.
It is defined piecewise over the following productions:
CharacterClassEscape
::
d
D
s
S
w
W
P{
UnicodePropertyValueExpression
}
UnicodePropertyValueExpression
::
UnicodePropertyName
=
UnicodePropertyValue
NestedClass ::
[^
ClassContents
]
ClassContents ::
[empty]
NonemptyClassRanges
ClassSetOperand
::
ClassSetCharacter
Return false .
UnicodePropertyValueExpression
:: LoneUnicodePropertyNameOrValue
If the source text
matched by LoneUnicodePropertyNameOrValue
is a binary property of strings listed in the “Property name ” column of
Table 71 ,
return true .
Return false .
ClassUnion ::
ClassSetRange
ClassUnion opt
If the ClassUnion is
present, return MayContainStrings
of the ClassUnion .
Return false .
ClassUnion ::
ClassSetOperand
ClassUnion opt
If MayContainStrings
of the ClassSetOperand is
true , return true .
If ClassUnion is
present, return MayContainStrings
of the ClassUnion .
Return false .
ClassIntersection
::
ClassSetOperand
&&
ClassSetOperand
If MayContainStrings
of the first ClassSetOperand is
false , return false .
If MayContainStrings
of the second ClassSetOperand is
false , return false .
Return true .
ClassIntersection
::
ClassIntersection
&&
ClassSetOperand
If MayContainStrings
of the ClassIntersection is
false , return false .
If MayContainStrings
of the ClassSetOperand is
false , return false .
Return true .
ClassSubtraction
::
ClassSetOperand
--
ClassSetOperand
Return MayContainStrings
of the first ClassSetOperand .
ClassSubtraction
::
ClassSubtraction
--
ClassSetOperand
Return MayContainStrings
of the ClassSubtraction .
ClassStringDisjunctionContents
::
ClassString
|
ClassStringDisjunctionContents
If MayContainStrings
of the ClassString
is true , return true .
Return MayContainStrings
of the ClassStringDisjunctionContents .
ClassString ::
[empty]
Return true .
ClassString ::
NonEmptyClassString
Return MayContainStrings
of the NonEmptyClassString .
NonEmptyClassString
::
ClassSetCharacter
NonEmptyClassString opt
If NonEmptyClassString is
present, return true .
Return false .
22.2.1.9 Static Semantics: GroupSpecifiersThatMatch (
thisGroupName )
The abstract operation GroupSpecifiersThatMatch takes argument thisGroupName (a
GroupName Parse
Node ) and returns a List of GroupSpecifier Parse
Nodes . It performs the following steps when called:
Let name be the CapturingGroupName
of thisGroupName .
Let pattern be the Pattern containing
thisGroupName .
Let result be a new empty List .
For each GroupSpecifier gs that
pattern contains, do
If the CapturingGroupName
of gs is name , then
Append gs to result .
Return result .
22.2.1.10 Static Semantics: CapturingGroupName
The syntax-directed
operation CapturingGroupName takes no arguments and returns a String.
It is defined piecewise over the following productions:
GroupName ::
<
RegExpIdentifierName
>
Let idTextUnescaped be the RegExpIdentifierCodePoints
of RegExpIdentifierName .
Return CodePointsToString (idTextUnescaped ).
22.2.1.11 Static Semantics: RegExpIdentifierCodePoints
The syntax-directed
operation RegExpIdentifierCodePoints takes no arguments and returns a
List of code points.
It is defined piecewise over the following productions:
RegExpIdentifierName
:: RegExpIdentifierStart
Let cp be the RegExpIdentifierCodePoint
of RegExpIdentifierStart .
Return « cp ».
RegExpIdentifierName
::
RegExpIdentifierName
RegExpIdentifierPart
Let cps be the RegExpIdentifierCodePoints
of the derived RegExpIdentifierName .
Let cp be the RegExpIdentifierCodePoint
of RegExpIdentifierPart .
Return the list-concatenation of
cps and « cp ».
22.2.1.12 Static Semantics: RegExpIdentifierCodePoint
The syntax-directed
operation RegExpIdentifierCodePoint takes no arguments and returns a
code point. It is defined piecewise over the following productions:
RegExpIdentifierStart
:: IdentifierStartChar
Return the code point matched by IdentifierStartChar .
RegExpIdentifierPart
:: IdentifierPartChar
Return the code point matched by IdentifierPartChar .
RegExpIdentifierStart
::
\
RegExpUnicodeEscapeSequence
RegExpIdentifierPart
::
\
RegExpUnicodeEscapeSequence
Return the code point whose numeric value is the CharacterValue
of RegExpUnicodeEscapeSequence .
RegExpIdentifierStart
::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpIdentifierPart
::
UnicodeLeadSurrogate
UnicodeTrailSurrogate
Let lead be the code unit whose numeric value is the numeric value of the
code point matched by UnicodeLeadSurrogate .
Let trail be the code unit whose numeric value is the numeric value of
the code point matched by UnicodeTrailSurrogate .
Return UTF16SurrogatePairToCodePoint (lead ,
trail ).
22.2.2 Pattern Semantics
A regular expression pattern is converted into an Abstract Closure using the
process described below. An implementation is encouraged to use more efficient algorithms than
the ones listed below, as long as the results are the same. The Abstract
Closure is used as the value of a RegExp object's [[RegExpMatcher]] internal slot.
A Pattern is a BMP pattern if its
associated flags contain neither a u nor a v. Otherwise, it is a
Unicode pattern. A BMP pattern matches against a String interpreted as consisting of a sequence
of 16-bit values that are Unicode code points in the range of the Basic Multilingual Plane. A
Unicode pattern matches against a String interpreted as consisting of Unicode code points
encoded using UTF-16. In the context of describing the behaviour of a BMP pattern “character”
means a single 16-bit Unicode BMP code point. In the context of describing the behaviour of a
Unicode pattern “character” means a UTF-16 encoded code point (6.1.4 ). In either
context, “character value” means the numeric value of the corresponding non-encoded code point.
The syntax and semantics of Pattern
is defined as if the source text for the Pattern was a List of SourceCharacter values where
each SourceCharacter
corresponds to a Unicode code point. If a BMP pattern contains a non-BMP SourceCharacter the entire
pattern is encoded using UTF-16 and the individual code units of that encoding are used as the
elements of the List .
Note
For example, consider a pattern expressed in source text as the single non-BMP character
U+1D11E (MUSICAL SYMBOL G CLEF). Interpreted as a Unicode pattern, it would be a single
element (character) List consisting of
the single code point U+1D11E. However, interpreted as a BMP pattern, it is first UTF-16
encoded to produce a two element List consisting of
the code units 0xD834 and 0xDD1E.
Patterns are passed to the RegExp constructor as ECMAScript String values in
which non-BMP characters are UTF-16 encoded. For example, the single character MUSICAL
SYMBOL G CLEF pattern, expressed as a String value, is a String of
length 2 whose elements were the code units 0xD834 and 0xDD1E. So no further translation
of the string would be necessary to process it as a BMP pattern consisting of two
pattern characters. However, to process it as a Unicode pattern UTF16SurrogatePairToCodePoint
must be used in producing a List whose sole
element is a single pattern character, the code point U+1D11E.
An implementation may not actually perform such translations to or from UTF-16, but the
semantics of this specification requires that the result of pattern matching be as if
such translations were performed.
22.2.2.1 Notation
The descriptions below use the following internal data structures:
A CharSetElement is one of the two following entities:
If rer .[[UnicodeSets]] is
false , then a CharSetElement is a character in the sense of
the Pattern Semantics above.
If rer .[[UnicodeSets]] is
true , then a CharSetElement is a sequence whose elements are
characters in the sense of the Pattern Semantics above. This includes the empty
sequence, sequences of one character, and sequences of more than one character.
For convenience, when working with CharSetElements of this kind, an individual
character is treated interchangeably with a sequence of one character.
A CharSet is a
mathematical set of CharSetElements.
A CaptureRange is a Record { [[StartIndex]] , [[EndIndex]] } that
represents the range of characters included in a capture, where [[StartIndex]] is an integer representing the start
index (inclusive) of the range within Input , and [[EndIndex]] is an integer representing the end index (exclusive) of
the range within Input . For any CaptureRange , these
indices must satisfy the invariant that [[StartIndex]] ≤ [[EndIndex]] .
A MatchState is a Record { [[Input]] , [[EndIndex]] , [[Captures]] } where [[Input]] is a
List of characters
representing the String being matched, [[EndIndex]] is an
integer , and
[[Captures]] is a List of values,
one for each left-capturing
parenthesis in the pattern. MatchStates are used to
represent partial match states in the regular expression matching algorithms. The [[EndIndex]] is one plus the index of the last input character
matched so far by the pattern, while [[Captures]] holds the
results of capturing parentheses. The n th element of [[Captures]] is either a CaptureRange
representing the range of characters captured by the n th set of
capturing parentheses, or undefined if the n th
set of capturing parentheses hasn't been reached yet. Due to backtracking, many
MatchStates may be in use at any time
during the matching process.
A MatcherContinuation is an Abstract Closure that
takes one MatchState argument and returns either
a MatchState or
failure . The MatcherContinuation attempts
to match the remaining portion (specified by the closure's captured values) of the
pattern against Input , starting at the intermediate state given by its
MatchState argument. If the match
succeeds, the MatcherContinuation returns
the final MatchState that it reached; if the
match fails, the MatcherContinuation returns
failure .
A Matcher is an
Abstract Closure that takes two
arguments—a MatchState and a MatcherContinuation —and
returns either a MatchState or
failure . A Matcher attempts to match a middle
subpattern (specified by the closure's captured values) of the pattern against the
MatchState 's [[Input]] , starting at the intermediate state given by its
MatchState argument. The MatcherContinuation argument
should be a closure that matches the rest of the pattern. After matching the subpattern
of a pattern to obtain a new MatchState , the Matcher then calls MatcherContinuation on that
new MatchState to test if the rest of the
pattern can match as well. If it can, the Matcher returns the
MatchState returned by MatcherContinuation ; if not,
the Matcher may try different choices at its
choice points, repeatedly calling MatcherContinuation until it
either succeeds or all possibilities have been exhausted.
22.2.2.1.1 RegExp Records
A RegExp Record is a Record value used
to store information about a RegExp that is needed during compilation and possibly
during matching.
It has the following fields:
Table 68: RegExp Record Fields
Field Name
Value
Meaning
[[IgnoreCase]]
a Boolean
indicates whether "i" appears in the RegExp's
flags
[[Multiline]]
a Boolean
indicates whether "m" appears in the RegExp's
flags
[[DotAll]]
a Boolean
indicates whether "s" appears in the RegExp's
flags
[[Unicode]]
a Boolean
indicates whether "u" appears in the RegExp's
flags
[[UnicodeSets]]
a Boolean
indicates whether "v" appears in the RegExp's
flags
[[CapturingGroupsCount]]
a non-negative integer
the number of left-capturing
parentheses in the RegExp's pattern
22.2.2.2 Runtime Semantics: CompilePattern
The syntax-directed
operation CompilePattern takes argument rer (a RegExp
Record ) and returns an Abstract Closure that
takes a List of characters and
a non-negative integer and returns either a MatchState or
failure . It is defined piecewise over the following productions:
Pattern :: Disjunction
Let m be CompileSubpattern of Disjunction with
arguments rer and forward .
Return a new Abstract Closure with parameters
(Input , index ) that captures rer and m
and performs the following steps when called:
Assert : Input is a
List
of characters.
Assert : 0 ≤ index ≤ the
number of elements in Input .
Let c be a new MatcherContinuation
with parameters (y ) that captures nothing and performs the
following steps when called:
Assert : y is a
MatchState .
Return y .
Let cap be a List
of rer .[[CapturingGroupsCount]]
undefined values, indexed 1 through rer .[[CapturingGroupsCount]] .
Let x be the MatchState
{ [[Input]] : Input , [[EndIndex]] : index , [[Captures]] : cap }.
Return m (x , c ).
Note
A Pattern compiles to an Abstract Closure value.
RegExpBuiltinExec can then
apply this procedure to a List of
characters and an offset within that List to
determine whether the pattern would match starting at exactly that offset within the
List , and, if
it does match, what the values of the capturing parentheses would be. The algorithms
in 22.2.2 are designed so that
compiling a pattern may throw a SyntaxError exception; on the
other hand, once the pattern is successfully compiled, applying the resulting
Abstract Closure to find a match
in a List of
characters cannot throw an exception (except for any implementation-defined
exceptions that can occur anywhere such as out-of-memory).
22.2.2.3 Runtime Semantics: CompileSubpattern
The syntax-directed
operation CompileSubpattern takes arguments rer (a
RegExp
Record ) and direction (forward or
backward ) and returns a Matcher .
Note 1
This section is amended in B.1.2.5 .
It is defined piecewise over the following productions:
Disjunction ::
Alternative
|
Disjunction
Let m1 be CompileSubpattern of Alternative with
arguments rer and direction .
Let m2 be CompileSubpattern of Disjunction with
arguments rer and direction .
Return MatchTwoAlternatives (m1 ,
m2 ).
Note 2
The | regular expression operator separates two alternatives. The
pattern first tries to match the left Alternative (followed by the sequel of
the regular expression); if it fails, it tries to match the right Disjunction (followed
by the sequel of the regular expression). If the left Alternative , the right Disjunction , and the
sequel all have choice points, all choices in the sequel are tried before moving on
to the next choice in the left Alternative . If choices in the left
Alternative are
exhausted, the right Disjunction is tried instead of the
left Alternative .
Any capturing parentheses inside a portion of the pattern skipped by |
produce undefined values instead of Strings. Thus, for example,
/a|ab/.exec ("abc" )
returns the result "a" and not "ab" . Moreover,
/((a)|(ab))((c)|(bc))/.exec ("abc" )
returns the array
["abc" , "a" , "a" , undefined , "bc" , undefined , "bc" ]
and not
["abc" , "ab" , undefined , "ab" , "c" , "c" , undefined ]
The order in which the two alternatives are tried is independent of the value of
direction .
Alternative ::
[empty]
Return EmptyMatcher ().
Alternative ::
Alternative
Term
Let m1 be CompileSubpattern of Alternative with
arguments rer and direction .
Let m2 be CompileSubpattern of Term with arguments
rer and direction .
Return MatchSequence (m1 ,
m2 , direction ).
Note 3
Consecutive Term s try to
simultaneously match consecutive portions of Input . When
direction is forward , if the left Alternative , the right
Term , and the sequel of
the regular expression all have choice points, all choices in the sequel are tried
before moving on to the next choice in the right Term , and all choices in the right Term are tried before moving
on to the next choice in the left Alternative . When direction
is backward , the evaluation order of Alternative and Term are reversed.
Term :: Assertion
Return CompileAssertion of Assertion with argument
rer .
Note 4
The resulting Matcher is independent of
direction .
Term :: Atom
Return CompileAtom of Atom with arguments
rer and direction .
Term ::
Atom
Quantifier
Let m be CompileAtom of Atom with arguments
rer and direction .
Let q be CompileQuantifier of Quantifier .
Assert :
q .[[Min]] ≤ q .[[Max]] .
Let parenIndex be CountLeftCapturingParensBefore (Term ).
Let parenCount be CountLeftCapturingParensWithin (Atom ).
Return a new Matcher with parameters
(x , c ) that captures m , q ,
parenIndex , and parenCount and performs the following steps
when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Return RepeatMatcher (m ,
q .[[Min]] , q .[[Max]] , q .[[Greedy]] , x , c ,
parenIndex , parenCount ).
22.2.2.3.1 RepeatMatcher ( m , min ,
max , greedy , x , c , parenIndex ,
parenCount )
The abstract operation RepeatMatcher takes arguments m (a Matcher ), min (a non-negative
integer ),
max (a non-negative integer or +∞), greedy (a Boolean),
x (a MatchState ), c (a MatcherContinuation ),
parenIndex (a non-negative integer ), and parenCount (a
non-negative integer ) and returns either a MatchState or
failure . It performs the following steps when called:
If max = 0, return c (x ).
Let d be a new MatcherContinuation
with parameters (y ) that captures m , min ,
max , greedy , x , c ,
parenIndex , and parenCount and performs the following
steps when called:
Assert : y is a
MatchState .
If min = 0 and y .[[EndIndex]] = x .[[EndIndex]] , return
failure .
If min = 0, let min2 be 0; otherwise let
min2 be min - 1.
If max = +∞, let max2 be +∞; otherwise let
max2 be max - 1.
Return RepeatMatcher (m ,
min2 , max2 , greedy , y ,
c , parenIndex , parenCount ).
Let cap be a copy of x .[[Captures]] .
For each integer k in
the inclusive interval from
parenIndex + 1 to parenIndex + parenCount , set
cap [k ] to undefined .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
Let xr be the MatchState { [[Input]] : Input , [[EndIndex]] : e , [[Captures]] : cap }.
If min ≠ 0, return m (xr , d ).
If greedy is false , then
Let z be c (x ).
If z is not failure , return
z .
Return m (xr , d ).
Let z be m (xr , d ).
If z is not failure , return z .
Return c (x ).
Note 1
An Atom followed by a
Quantifier is
repeated the number of times specified by the Quantifier . A Quantifier can be
non-greedy, in which case the Atom pattern is repeated as few times as
possible while still matching the sequel, or it can be greedy, in which case the
Atom pattern is
repeated as many times as possible while still matching the sequel. The Atom pattern is repeated
rather than the input character sequence that it matches, so different
repetitions of the Atom can match different input
substrings.
Note 2
If the Atom and the
sequel of the regular expression all have choice points, the Atom is first matched as
many (or as few, if non-greedy) times as possible. All choices in the sequel are
tried before moving on to the next choice in the last repetition of Atom . All choices in the
last (nth ) repetition of Atom are tried before moving on to the
next choice in the next-to-last (n - 1)st repetition of Atom ; at which point it
may turn out that more or fewer repetitions of Atom are now possible; these are
exhausted (again, starting with either as few or as many as possible) before
moving on to the next choice in the (n - 1)st repetition of Atom and so on.
Compare
/a[a-z]{2 ,4 }/.exec ("abcdefghi" )
which returns "abcde" with
/a[a-z]{2 ,4 }?/.exec ("abcdefghi" )
which returns "abc" .
Consider also
/(aa|aabaac|ba|b|c)*/.exec ("aabaac" )
which, by the choice point ordering above, returns the array
["aaba" , "ba" ]
and not any of:
["aabaac" , "aabaac" ]
["aabaac" , "c" ]
The above ordering of choice points can be used to write a regular expression
that calculates the greatest common divisor of two numbers (represented in unary
notation). The following example calculates the gcd of 10 and 15:
"aaaaaaaaaa,aaaaaaaaaaaaaaa" .replace (/^(a+)\1*,\1+$/ , "$1" )
which returns the gcd in unary notation "aaaaa" .
Note 3
Step 4 of the
RepeatMatcher clears Atom 's captures each time Atom is repeated. We can
see its behaviour in the regular expression
/(z)((a+)?(b+)?(c))*/.exec ("zaacbbbcac" )
which returns the array
["zaacbbbcac" , "z" , "ac" , "a" , undefined , "c" ]
and not
["zaacbbbcac" , "z" , "ac" , "a" , "bbb" , "c" ]
because each iteration of the outermost * clears all captured
Strings contained in the quantified Atom , which in this case includes capture
Strings numbered 2, 3, 4, and 5.
Note 4
Step 2.b of the RepeatMatcher
states that once the minimum number of repetitions has been satisfied, any more
expansions of Atom
that match the empty character sequence are not considered for further
repetitions. This prevents the regular expression engine from falling into an
infinite loop on patterns such as:
/(a*)*/.exec ("b" )
or the slightly more complicated:
/(a*)b\1 +/.exec ("baaaac" )
which returns the array
["b" , "" ]
22.2.2.3.2 EmptyMatcher ( )
The abstract operation EmptyMatcher takes no arguments and returns a Matcher . It performs the following steps
when called:
Return a new Matcher with parameters
(x , c ) that captures nothing and performs the following
steps when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Return c (x ).
22.2.2.3.3 MatchTwoAlternatives ( m1 ,
m2 )
The abstract operation MatchTwoAlternatives takes arguments m1 (a Matcher ) and m2 (a Matcher ) and returns a Matcher . It performs the following steps
when called:
Return a new Matcher with parameters
(x , c ) that captures m1 and m2 and
performs the following steps when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Let r be m1 (x , c ).
If r is not failure , return
r .
Return m2 (x , c ).
22.2.2.3.4 MatchSequence ( m1 , m2 ,
direction )
The abstract operation MatchSequence takes arguments m1 (a Matcher ), m2 (a Matcher ), and direction
(forward or backward ) and returns a
Matcher . It performs the following steps
when called:
If direction is forward , then
Return a new Matcher with parameters
(x , c ) that captures m1 and
m2 and performs the following steps when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures c and
m2 and performs the following steps when called:
Assert :
y is a MatchState .
Return m2 (y , c ).
Return m1 (x , d ).
Else,
Assert : direction is
backward .
Return a new Matcher with parameters
(x , c ) that captures m1 and
m2 and performs the following steps when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures c and
m1 and performs the following steps when called:
Assert :
y is a MatchState .
Return m1 (y , c ).
Return m2 (x , d ).
22.2.2.4 Runtime Semantics: CompileAssertion
The syntax-directed
operation CompileAssertion takes argument rer (a RegExp
Record ) and returns a Matcher .
Note 1
This section is amended in B.1.2.6 .
It is defined piecewise over the following productions:
Assertion :: ^
Return a new Matcher with parameters
(x , c ) that captures rer and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
If e = 0, or if rer .[[Multiline]] is true and the
character Input [e - 1] is matched by LineTerminator , then
Return c (x ).
Return failure .
Note 2
Even when the y flag is used with a pattern, ^ always
matches only at the beginning of Input , or (if rer .[[Multiline]] is true ) at the beginning
of a line.
Assertion :: $
Return a new Matcher with parameters
(x , c ) that captures rer and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
Let InputLength be the number of elements in Input .
If e = InputLength , or if rer .[[Multiline]] is true and the
character Input [e ] is matched by LineTerminator , then
Return c (x ).
Return failure .
Assertion :: \b
Return a new Matcher with parameters
(x , c ) that captures rer and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
Let a be IsWordChar (rer ,
Input , e - 1).
Let b be IsWordChar (rer ,
Input , e ).
If a is true and b is
false , or if a is false and
b is true , return c (x ).
Return failure .
Assertion :: \B
Return a new Matcher with parameters
(x , c ) that captures rer and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
Let a be IsWordChar (rer ,
Input , e - 1).
Let b be IsWordChar (rer ,
Input , e ).
If a is true and b is
true , or if a is false and
b is false , return c (x ).
Return failure .
Assertion ::
(?=
Disjunction
)
Let m be CompileSubpattern of Disjunction with
arguments rer and forward .
Return a new Matcher with parameters
(x , c ) that captures m and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures nothing and performs the
following steps when called:
Assert : y is a
MatchState .
Return y .
Let r be m (x , d ).
If r is failure , return
failure .
Assert : r is a MatchState .
Let cap be r .[[Captures]] .
Let Input be x .[[Input]] .
Let xe be x .[[EndIndex]] .
Let z be the MatchState
{ [[Input]] : Input , [[EndIndex]] : xe , [[Captures]] : cap }.
Return c (z ).
Note 3
The form (?= Disjunction ) specifies a
zero-width positive lookahead. In order for it to succeed, the pattern inside
Disjunction must
match at the current position, but the current position is not advanced before
matching the sequel. If Disjunction can match at the current
position in several ways, only the first one is tried. Unlike other regular
expression operators, there is no backtracking into a (?= form (this
unusual behaviour is inherited from Perl). This only matters when the Disjunction contains
capturing parentheses and the sequel of the pattern contains backreferences to those
captures.
For example,
/(?=(a+))/.exec ("baaabac" )
matches the empty String immediately after the first b and therefore
returns the array:
["" , "aaa" ]
To illustrate the lack of backtracking into the lookahead, consider:
/(?=(a+))a*b\1 /.exec ("baaabac" )
This expression returns
["aba" , "a" ]
and not:
["aaaba" , "a" ]
Assertion ::
(?!
Disjunction
)
Let m be CompileSubpattern of Disjunction with
arguments rer and forward .
Return a new Matcher with parameters
(x , c ) that captures m and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures nothing and performs the
following steps when called:
Assert : y is a
MatchState .
Return y .
Let r be m (x , d ).
If r is not failure , return
failure .
Return c (x ).
Note 4
The form (?! Disjunction ) specifies a
zero-width negative lookahead. In order for it to succeed, the pattern inside
Disjunction must
fail to match at the current position. The current position is not advanced before
matching the sequel. Disjunction can contain capturing
parentheses, but backreferences to them only make sense from within Disjunction itself.
Backreferences to these capturing parentheses from elsewhere in the pattern always
return undefined because the negative lookahead must fail for the
pattern to succeed. For example,
/(.*?)a (?!(a+)b\2c)\2 (.*)/.exec ("baaabaac" )
looks for an a not immediately followed by some positive number n of
a's, a b, another n a's (specified by the
first \2) and a c. The second \2 is outside
the negative lookahead, so it matches against undefined and
therefore always succeeds. The whole expression returns the array:
["baaabaac" , "ba" , undefined , "abaac" ]
Assertion ::
(?<=
Disjunction
)
Let m be CompileSubpattern of Disjunction with
arguments rer and backward .
Return a new Matcher with parameters
(x , c ) that captures m and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures nothing and performs the
following steps when called:
Assert : y is a
MatchState .
Return y .
Let r be m (x , d ).
If r is failure , return
failure .
Assert : r is a MatchState .
Let cap be r .[[Captures]] .
Let Input be x .[[Input]] .
Let xe be x .[[EndIndex]] .
Let z be the MatchState
{ [[Input]] : Input , [[EndIndex]] : xe , [[Captures]] : cap }.
Return c (z ).
Assertion ::
(?<!
Disjunction
)
Let m be CompileSubpattern of Disjunction with
arguments rer and backward .
Return a new Matcher with parameters
(x , c ) that captures m and performs the following
steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures nothing and performs the
following steps when called:
Assert : y is a
MatchState .
Return y .
Let r be m (x , d ).
If r is not failure , return
failure .
Return c (x ).
22.2.2.4.1 IsWordChar ( rer , Input ,
e )
The abstract operation IsWordChar takes arguments rer (a RegExp
Record ), Input (a List of
characters), and e (an integer ) and returns a Boolean. It performs the
following steps when called:
Let InputLength be the number of elements in Input .
If e = -1 or e = InputLength , return
false .
Let c be the character Input [e ].
If WordCharacters (rer )
contains c , return true .
Return false .
22.2.2.5 Runtime Semantics: CompileQuantifier
The syntax-directed
operation CompileQuantifier takes no arguments and returns a
Record with fields
[[Min]] (a non-negative integer ), [[Max]] (a non-negative integer or +∞), and [[Greedy]] (a Boolean). It is defined piecewise over the following
productions:
Quantifier ::
QuantifierPrefix
Let qp be CompileQuantifierPrefix
of QuantifierPrefix .
Return the Record { [[Min]] : qp .[[Min]] ,
[[Max]] : qp .[[Max]] ,
[[Greedy]] : true }.
Quantifier ::
QuantifierPrefix
?
Let qp be CompileQuantifierPrefix
of QuantifierPrefix .
Return the Record { [[Min]] : qp .[[Min]] ,
[[Max]] : qp .[[Max]] ,
[[Greedy]] : false }.
22.2.2.6 Runtime Semantics: CompileQuantifierPrefix
The syntax-directed
operation CompileQuantifierPrefix takes no arguments and returns a
Record with fields
[[Min]] (a non-negative integer ) and [[Max]] (a non-negative integer or +∞). It is defined piecewise over the
following productions:
QuantifierPrefix
:: *
Return the Record { [[Min]] : 0, [[Max]] : +∞ }.
QuantifierPrefix
:: +
Return the Record { [[Min]] : 1, [[Max]] : +∞ }.
QuantifierPrefix
:: ?
Return the Record { [[Min]] : 0, [[Max]] : 1 }.
QuantifierPrefix
::
{
DecimalDigits
}
Let i be the MV of DecimalDigits (see 12.9.3 ).
Return the Record { [[Min]] : i , [[Max]] :
i }.
QuantifierPrefix
::
{
DecimalDigits
,}
Let i be the MV of DecimalDigits .
Return the Record { [[Min]] : i , [[Max]] :
+∞ }.
QuantifierPrefix
::
{
DecimalDigits
,
DecimalDigits
}
Let i be the MV of the first DecimalDigits .
Let j be the MV of the second DecimalDigits .
Return the Record { [[Min]] : i , [[Max]] :
j }.
22.2.2.7 Runtime Semantics: CompileAtom
The syntax-directed
operation CompileAtom takes arguments rer (a RegExp
Record ) and direction (forward or
backward ) and returns a Matcher .
Note 1
This section is amended in B.1.2.7 .
It is defined piecewise over the following productions:
Atom :: PatternCharacter
Let ch be the character matched by PatternCharacter .
Let A be a one-element CharSet containing the
character ch .
Return CharacterSetMatcher (rer ,
A , false , direction ).
Atom :: .
Let A be AllCharacters (rer ).
If rer .[[DotAll]] is not
true , then
Remove from A all characters corresponding to a code point on the
right-hand side of the LineTerminator production.
Return CharacterSetMatcher (rer ,
A , false , direction ).
Atom :: CharacterClass
Let cc be CompileCharacterClass of
CharacterClass
with argument rer .
Let cs be cc .[[CharSet]] .
If rer .[[UnicodeSets]] is
false , or if every CharSetElement of
cs consists of a single character (including if cs is empty),
return CharacterSetMatcher (rer ,
cs , cc .[[Invert]] ,
direction ).
Assert :
cc .[[Invert]] is false .
Let lm be an empty List of
Matchers .
For each CharSetElement s in
cs containing more than 1 character, iterating in descending order of
length, do
Let cs2 be a one-element CharSet
containing the last code point of s .
Let m2 be CharacterSetMatcher (rer ,
cs2 , false , direction ).
For each code point c1 in s , iterating backwards from
its second-to-last code point, do
Let cs1 be a one-element CharSet containing
c1 .
Let m1 be CharacterSetMatcher (rer ,
cs1 , false , direction ).
Set m2 to MatchSequence (m1 ,
m2 , direction ).
Append m2 to lm .
Let singles be the CharSet containing every CharSetElement of cs
that consists of a single character.
Append CharacterSetMatcher (rer ,
singles , false , direction ) to
lm .
If cs contains the empty sequence of characters, append EmptyMatcher () to lm .
Let m2 be the last Matcher in lm .
For each Matcher m1 of
lm , iterating backwards from its second-to-last element, do
Set m2 to MatchTwoAlternatives (m1 ,
m2 ).
Return m2 .
Atom ::
(
GroupSpecifier opt
Disjunction
)
Let m be CompileSubpattern of Disjunction with
arguments rer and direction .
Let parenIndex be CountLeftCapturingParensBefore (Atom ).
Return a new Matcher with parameters
(x , c ) that captures direction , m , and
parenIndex and performs the following steps when called:
Assert : x is a MatchState .
Assert : c is a MatcherContinuation .
Let d be a new MatcherContinuation
with parameters (y ) that captures x , c ,
direction , and parenIndex and performs the following
steps when called:
Assert : y is a
MatchState .
Let cap be a copy of y .[[Captures]] .
Let Input be x .[[Input]] .
Let xe be x .[[EndIndex]] .
Let ye be y .[[EndIndex]] .
If direction is forward , then
Assert : xe
≤ ye .
Let r be the CaptureRange
{ [[StartIndex]] : xe ,
[[EndIndex]] : ye }.
Else,
Assert :
direction is backward .
Assert : ye
≤ xe .
Let r be the CaptureRange
{ [[StartIndex]] : ye ,
[[EndIndex]] : xe }.
Set cap [parenIndex + 1] to r .
Let z be the MatchState { [[Input]] : Input , [[EndIndex]] : ye , [[Captures]] : cap }.
Return c (z ).
Return m (x , d ).
Note 2
Parentheses of the form ( Disjunction ) serve both
to group the components of the Disjunction pattern together and to
save the result of the match. The result can be used either in a backreference
(\ followed by a non-zero decimal number), referenced in a replace
String, or returned as part of an array from the regular expression matching
Abstract Closure . To inhibit the
capturing behaviour of parentheses, use the form (?: Disjunction
) instead.
Atom ::
(?
RegularExpressionModifiers
:
Disjunction
)
Let addModifiers be the source text
matched by RegularExpressionModifiers .
Let removeModifiers be the empty String.
Let modifiedRer be UpdateModifiers (rer ,
CodePointsToString (addModifiers ),
removeModifiers ).
Return CompileSubpattern of Disjunction with
arguments modifiedRer and direction .
Atom ::
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction
)
Let addModifiers be the source text
matched by the first RegularExpressionModifiers .
Let removeModifiers be the source text
matched by the second RegularExpressionModifiers .
Let modifiedRer be UpdateModifiers (rer ,
CodePointsToString (addModifiers ),
CodePointsToString (removeModifiers )).
Return CompileSubpattern of Disjunction with
arguments modifiedRer and direction .
AtomEscape ::
DecimalEscape
Let n be the CapturingGroupNumber
of DecimalEscape .
Assert :
n ≤ rer .[[CapturingGroupsCount]] .
Return BackreferenceMatcher (rer ,
« n », direction ).
Note 3
An escape sequence of the form \ followed by a non-zero decimal number
n matches the result of the n th set of capturing
parentheses (22.2.2.1 ). It is an error if the
regular expression has fewer than n capturing parentheses. If the regular
expression has n or more capturing parentheses but the
n th one is undefined because it has not
captured anything, then the backreference always succeeds.
AtomEscape ::
CharacterEscape
Let cv be the CharacterValue
of CharacterEscape .
Let ch be the character whose character value is cv .
Let A be a one-element CharSet containing the
character ch .
Return CharacterSetMatcher (rer ,
A , false , direction ).
AtomEscape ::
CharacterClassEscape
Let cs be CompileToCharSet of CharacterClassEscape with
argument rer .
If rer .[[UnicodeSets]] is
false , or if every CharSetElement of
cs consists of a single character (including if cs is empty),
return CharacterSetMatcher (rer ,
cs , false , direction ).
Let lm be an empty List of
Matchers .
For each CharSetElement s in
cs containing more than 1 character, iterating in descending order of
length, do
Let cs2 be a one-element CharSet
containing the last code point of s .
Let m2 be CharacterSetMatcher (rer ,
cs2 , false , direction ).
For each code point c1 in s , iterating backwards from
its second-to-last code point, do
Let cs1 be a one-element CharSet containing
c1 .
Let m1 be CharacterSetMatcher (rer ,
cs1 , false , direction ).
Set m2 to MatchSequence (m1 ,
m2 , direction ).
Append m2 to lm .
Let singles be the CharSet containing every CharSetElement of cs
that consists of a single character.
Append CharacterSetMatcher (rer ,
singles , false , direction ) to
lm .
If cs contains the empty sequence of characters, append EmptyMatcher () to lm .
Let m2 be the last Matcher in lm .
For each Matcher m1 of
lm , iterating backwards from its second-to-last element, do
Set m2 to MatchTwoAlternatives (m1 ,
m2 ).
Return m2 .
AtomEscape ::
k
GroupName
Let matchingGroupSpecifiers be GroupSpecifiersThatMatch (GroupName ).
Let parenIndices be a new empty List .
For each GroupSpecifier
groupSpecifier of matchingGroupSpecifiers , do
Let parenIndex be CountLeftCapturingParensBefore (groupSpecifier ).
Append parenIndex to parenIndices .
Return BackreferenceMatcher (rer ,
parenIndices , direction ).
22.2.2.7.1 CharacterSetMatcher ( rer ,
A , invert , direction )
The abstract operation CharacterSetMatcher takes arguments rer (a RegExp
Record ), A (a CharSet ),
invert (a Boolean), and direction (forward
or backward ) and returns a Matcher . It performs the
following steps when called:
If rer .[[UnicodeSets]] is
true , then
Assert : invert is
false .
Assert : Every CharSetElement of
A consists of a single character.
Return a new Matcher with parameters
(x , c ) that captures rer , A ,
invert , and direction and performs the following steps
when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Let Input be x .[[Input]] .
Let e be x .[[EndIndex]] .
If direction is forward , let
f be e + 1.
Else, let f be e - 1.
Let InputLength be the number of elements in
Input .
If f < 0 or f > InputLength ,
return failure .
Let index be min (e , f ).
Let ch be the character Input [index ].
Let cc be Canonicalize (rer ,
ch ).
If there exists a CharSetElement in
A containing exactly one character a such that
Canonicalize (rer ,
a ) is cc , let found be
true ; otherwise let found be
false .
If invert is false and found is
false , return failure .
If invert is true and found is
true , return failure .
Let cap be x .[[Captures]] .
Let y be the MatchState { [[Input]] : Input , [[EndIndex]] : f , [[Captures]] : cap }.
Return c (y ).
22.2.2.7.2 BackreferenceMatcher ( rer ,
ns , direction )
The abstract operation BackreferenceMatcher takes arguments rer (a RegExp
Record ), ns (a List of positive
integers ),
and direction (forward or
backward ) and returns a Matcher . It performs the
following steps when called:
Return a new Matcher with parameters
(x , c ) that captures rer , ns , and
direction and performs the following steps when called:
Assert : x is a
MatchState .
Assert : c is a
MatcherContinuation .
Let Input be x .[[Input]] .
Let cap be x .[[Captures]] .
Let r be undefined .
For each integer n of
ns , do
If cap [n ] is not
undefined , then
Assert :
r is undefined .
Set r to cap [n ].
If r is undefined , return
c (x ).
Let e be x .[[EndIndex]] .
Let rs be r .[[StartIndex]] .
Let re be r .[[EndIndex]] .
Let len be re - rs .
If direction is forward , let
f be e + len .
Else, let f be e - len .
Let InputLength be the number of elements in
Input .
If f < 0 or f > InputLength ,
return failure .
Let g be min (e , f ).
If there exists an integer i in the
interval from 0 (inclusive) to
len (exclusive) such that Canonicalize (rer ,
Input [rs + i ]) is not Canonicalize (rer ,
Input [g + i ]), return
failure .
Let y be the MatchState { [[Input]] : Input , [[EndIndex]] : f , [[Captures]] : cap }.
Return c (y ).
22.2.2.7.3 Canonicalize ( rer , ch )
The abstract operation Canonicalize takes arguments rer (a RegExp
Record ) and ch (a character) and returns a character.
It performs the following steps when called:
If HasEitherUnicodeFlag (rer )
is true and rer .[[IgnoreCase]] is true , then
If the file CaseFolding.txt
of the Unicode Character Database provides a simple or common case
folding mapping for ch , return the result of applying that
mapping to ch .
Return ch .
If rer .[[IgnoreCase]] is
false , return ch .
Assert : ch is a UTF-16 code
unit.
Let cp be the code point whose numeric value is the numeric value of
ch .
Let u be toUppercase(« cp »), according to the
Unicode Default Case Conversion algorithm.
Let uStr be CodePointsToString (u ).
If the length of uStr ≠ 1, return ch .
Let cu be uStr 's single code unit element.
If the numeric value of ch ≥ 128 and the numeric value of
cu < 128, return ch .
Return cu .
Note
In case-insignificant matches when HasEitherUnicodeFlag (rer )
is true , all characters are implicitly case-folded using the
simple mapping provided by the Unicode Standard immediately before they are
compared. The simple mapping always maps to a single code point, so it does not
map, for example, ß (U+00DF LATIN SMALL LETTER SHARP S) to
ss or SS. It may however map code points outside the
Basic Latin block to code points within it—for example, ſ (U+017F
LATIN SMALL LETTER LONG S) case-folds to s (U+0073 LATIN SMALL
LETTER S) and K (U+212A KELVIN SIGN) case-folds to k
(U+006B LATIN SMALL LETTER K). Strings containing those code points are matched
by regular expressions such as /[a-z]/ui.
In case-insignificant matches when HasEitherUnicodeFlag (rer )
is false , the mapping is based on Unicode Default Case
Conversion algorithm toUppercase rather than toCasefold, which results in some
subtle differences. For example, Ω (U+2126 OHM SIGN) is mapped by
toUppercase to itself but by toCasefold to ω (U+03C9 GREEK SMALL
LETTER OMEGA) along with Ω (U+03A9 GREEK CAPITAL LETTER OMEGA), so
"\u2126" is matched by /[ω]/ui and
/[\u03A9]/ui but not by /[ω]/i or
/[\u03A9]/i. Also, no code point outside the Basic Latin block is
mapped to a code point within it, so strings such as "\u017F
ſ" and "\u212A K" are not matched by
/[a-z]/i.
22.2.2.7.4 UpdateModifiers ( rer , add ,
remove )
The abstract operation UpdateModifiers takes arguments rer (a RegExp
Record ), add (a String), and remove (a
String) and returns a RegExp Record . It performs the
following steps when called:
Assert : add and
remove have no elements in common.
Let ignoreCase be rer .[[IgnoreCase]] .
Let multiline be rer .[[Multiline]] .
Let dotAll be rer .[[DotAll]] .
Let unicode be rer .[[Unicode]] .
Let unicodeSets be rer .[[UnicodeSets]] .
Let capturingGroupsCount be rer .[[CapturingGroupsCount]] .
If remove contains "i" , set ignoreCase
to false .
Else if add contains "i" , set
ignoreCase to true .
If remove contains "m" , set multiline
to false .
Else if add contains "m" , set multiline
to true .
If remove contains "s" , set dotAll to
false .
Else if add contains "s" , set dotAll to
true .
Return the RegExp Record { [[IgnoreCase]] : ignoreCase , [[Multiline]] : multiline , [[DotAll]] : dotAll , [[Unicode]] : unicode , [[UnicodeSets]] : unicodeSets , [[CapturingGroupsCount]] :
capturingGroupsCount }.
22.2.2.8 Runtime Semantics: CompileCharacterClass
The syntax-directed
operation CompileCharacterClass takes argument rer (a
RegExp
Record ) and returns a Record with fields
[[CharSet]] (a CharSet ) and [[Invert]] (a Boolean). It is defined piecewise over the following
productions:
CharacterClass ::
[
ClassContents
]
Let A be CompileToCharSet of ClassContents with
argument rer .
Return the Record { [[CharSet]] : A , [[Invert]] : false }.
CharacterClass ::
[^
ClassContents
]
Let A be CompileToCharSet of ClassContents with
argument rer .
If rer .[[UnicodeSets]] is
true , then
Return the Record
{ [[CharSet]] : CharacterComplement (rer ,
A ), [[Invert]] :
false }.
Return the Record { [[CharSet]] : A , [[Invert]] : true }.
22.2.2.9 Runtime Semantics: CompileToCharSet
The syntax-directed
operation CompileToCharSet takes argument rer (a RegExp
Record ) and returns a CharSet .
Note 1
This section is amended in B.1.2.8 .
It is defined piecewise over the following productions:
ClassContents ::
[empty]
Return the empty CharSet .
NonemptyClassRanges
::
ClassAtom
NonemptyClassRangesNoDash
Let A be CompileToCharSet of ClassAtom with argument
rer .
Let B be CompileToCharSet of NonemptyClassRangesNoDash
with argument rer .
Return the union of CharSets A and
B .
NonemptyClassRanges
::
ClassAtom
-
ClassAtom
ClassContents
Let A be CompileToCharSet of the first
ClassAtom with
argument rer .
Let B be CompileToCharSet of the second
ClassAtom with
argument rer .
Let C be CompileToCharSet of ClassContents with
argument rer .
Let D be CharacterRange (A ,
B ).
Return the union of D and C .
NonemptyClassRangesNoDash
::
ClassAtomNoDash
NonemptyClassRangesNoDash
Let A be CompileToCharSet of ClassAtomNoDash
with argument rer .
Let B be CompileToCharSet of NonemptyClassRangesNoDash
with argument rer .
Return the union of CharSets A and
B .
NonemptyClassRangesNoDash
::
ClassAtomNoDash
-
ClassAtom
ClassContents
Let A be CompileToCharSet of ClassAtomNoDash
with argument rer .
Let B be CompileToCharSet of ClassAtom with argument
rer .
Let C be CompileToCharSet of ClassContents with
argument rer .
Let D be CharacterRange (A ,
B ).
Return the union of D and C .
Note 2
ClassContents can
expand into a single ClassAtom and/or ranges of two ClassAtom separated by
dashes. In the latter case the ClassContents includes all
characters between the first ClassAtom and the second ClassAtom , inclusive; an
error occurs if either ClassAtom does not represent a single
character (for example, if one is \w) or if the first ClassAtom 's character value is strictly
greater than the second ClassAtom 's character value.
Note 3
Even if the pattern ignores case, the case of the two ends of a range is significant
in determining which characters belong to the range. Thus, for example, the pattern
/[E-F]/i matches only the letters E, F,
e, and f, while the pattern /[E-f]/i matches
all uppercase and lowercase letters in the Unicode Basic Latin block as well as the
symbols [, \, ], ^,
_, and `.
Note 4
A - character can be treated literally or it can denote a range. It is
treated literally if it is the first or last character of ClassContents , the beginning or end
limit of a range specification, or immediately follows a range specification.
ClassAtom :: -
Return the CharSet containing the single
character - U+002D (HYPHEN-MINUS).
ClassAtomNoDash
:: SourceCharacter
but not one of \ or ] or
-
Return the CharSet containing the character
matched by SourceCharacter .
ClassEscape ::
b
-
CharacterEscape
Let cv be the CharacterValue
of this ClassEscape .
Let c be the character whose character value is cv .
Return the CharSet containing the single
character c .
Note 5
A ClassAtom can use
any of the escape sequences that are allowed in the rest of the regular expression
except for \b, \B, and backreferences. Inside a CharacterClass ,
\b means the backspace character, while \B and
backreferences raise errors. Using a backreference inside a ClassAtom causes an
error.
CharacterClassEscape
:: d
Return the ten-element CharSet containing the characters
0, 1, 2, 3, 4,
5, 6, 7, 8, and 9.
CharacterClassEscape
:: D
Let S be the CharSet returned by
CharacterClassEscape
:: d
.
Return CharacterComplement (rer ,
S ).
CharacterClassEscape
:: s
Return the CharSet containing all characters
corresponding to a code point on the right-hand side of the WhiteSpace or LineTerminator
productions.
CharacterClassEscape
:: S
Let S be the CharSet returned by
CharacterClassEscape
:: s
.
Return CharacterComplement (rer ,
S ).
CharacterClassEscape
:: w
Return MaybeSimpleCaseFolding (rer ,
WordCharacters (rer )).
CharacterClassEscape
:: W
Let S be the CharSet returned by
CharacterClassEscape
:: w
.
Return CharacterComplement (rer ,
S ).
CharacterClassEscape
::
p{
UnicodePropertyValueExpression
}
Return CompileToCharSet of UnicodePropertyValueExpression
with argument rer .
CharacterClassEscape
::
P{
UnicodePropertyValueExpression
}
Let S be CompileToCharSet of UnicodePropertyValueExpression
with argument rer .
Assert :
S contains only single code points.
Return CharacterComplement (rer ,
S ).
UnicodePropertyValueExpression
::
UnicodePropertyName
=
UnicodePropertyValue
Let ps be the source text
matched by UnicodePropertyName .
Let p be UnicodeMatchProperty (rer ,
ps ).
Assert :
p is a Unicode property name or property alias listed
in the “Property name and aliases” column of
Table 69 .
Let vs be the source text
matched by UnicodePropertyValue .
Let v be UnicodeMatchPropertyValue (p ,
vs ).
Let A be the CharSet containing all Unicode code
points whose character database definition includes the property p with
value v .
Return MaybeSimpleCaseFolding (rer ,
A ).
UnicodePropertyValueExpression
:: LoneUnicodePropertyNameOrValue
Let s be the source text
matched by LoneUnicodePropertyNameOrValue .
If UnicodeMatchPropertyValue (General_Category,
s ) is a Unicode property value or property value alias for the
General_Category (gc) property listed in PropertyValueAliases.txt ,
then
Return the CharSet containing all
Unicode code points whose character database definition includes the
property “General_Category” with value s .
Let p be UnicodeMatchProperty (rer ,
s ).
Assert :
p is a binary Unicode property or binary property alias listed in the
“Property name and aliases” column of Table 70 , or a binary
Unicode property of strings listed in the “Property name ”
column of Table
71 .
Let A be the CharSet containing all
CharSetElements whose character database definition includes the property
p with value “True”.
Return MaybeSimpleCaseFolding (rer ,
A ).
ClassUnion ::
ClassSetRange
ClassUnion opt
Let A be CompileToCharSet of ClassSetRange with
argument rer .
If ClassUnion is
present, then
Let B be CompileToCharSet of
ClassUnion
with argument rer .
Return the union of CharSets A and
B .
Return A .
ClassUnion ::
ClassSetOperand
ClassUnion opt
Let A be CompileToCharSet of ClassSetOperand
with argument rer .
If ClassUnion is
present, then
Let B be CompileToCharSet of
ClassUnion
with argument rer .
Return the union of CharSets A and
B .
Return A .
ClassIntersection
::
ClassSetOperand
&&
ClassSetOperand
Let A be CompileToCharSet of the first
ClassSetOperand
with argument rer .
Let B be CompileToCharSet of the second
ClassSetOperand
with argument rer .
Return the intersection of CharSets A and
B .
ClassIntersection
::
ClassIntersection
&&
ClassSetOperand
Let A be CompileToCharSet of the ClassIntersection
with argument rer .
Let B be CompileToCharSet of the ClassSetOperand
with argument rer .
Return the intersection of CharSets A and
B .
ClassSubtraction
::
ClassSetOperand
--
ClassSetOperand
Let A be CompileToCharSet of the first
ClassSetOperand
with argument rer .
Let B be CompileToCharSet of the second
ClassSetOperand
with argument rer .
Return the CharSet containing the
CharSetElements of A which are not also CharSetElements of B .
ClassSubtraction
::
ClassSubtraction
--
ClassSetOperand
Let A be CompileToCharSet of the ClassSubtraction
with argument rer .
Let B be CompileToCharSet of the ClassSetOperand
with argument rer .
Return the CharSet containing the
CharSetElements of A which are not also CharSetElements of B .
ClassSetRange ::
ClassSetCharacter
-
ClassSetCharacter
Let A be CompileToCharSet of the first
ClassSetCharacter with argument
rer .
Let B be CompileToCharSet of the second
ClassSetCharacter with argument
rer .
Return MaybeSimpleCaseFolding (rer ,
CharacterRange (A ,
B )).
Note 6
The result will often consist of two or more ranges. When UnicodeSets is
true and IgnoreCase is true , then MaybeSimpleCaseFolding (rer ,
[Ā-č]) will include only the odd-numbered code points of that range.
ClassSetOperand
:: ClassSetCharacter
Let A be CompileToCharSet of ClassSetCharacter
with argument rer .
Return MaybeSimpleCaseFolding (rer ,
A ).
ClassSetOperand
:: ClassStringDisjunction
Let A be CompileToCharSet of ClassStringDisjunction with
argument rer .
Return MaybeSimpleCaseFolding (rer ,
A ).
ClassSetOperand
:: NestedClass
Return CompileToCharSet of NestedClass with
argument rer .
NestedClass ::
[
ClassContents
]
Return CompileToCharSet of ClassContents with
argument rer .
NestedClass ::
[^
ClassContents
]
Let A be CompileToCharSet of ClassContents with
argument rer .
Return CharacterComplement (rer ,
A ).
NestedClass ::
\
CharacterClassEscape
Return CompileToCharSet of CharacterClassEscape with
argument rer .
ClassStringDisjunction
::
\q{
ClassStringDisjunctionContents
}
Return CompileToCharSet of ClassStringDisjunctionContents
with argument rer .
ClassStringDisjunctionContents
:: ClassString
Let s be CompileClassSetString of
ClassString with
argument rer .
Return the CharSet containing the one string
s .
ClassStringDisjunctionContents
::
ClassString
|
ClassStringDisjunctionContents
Let s be CompileClassSetString of
ClassString with
argument rer .
Let A be the CharSet containing the one string
s .
Let B be CompileToCharSet of ClassStringDisjunctionContents
with argument rer .
Return the union of CharSets A and
B .
ClassSetCharacter
::
SourceCharacter
but not ClassSetSyntaxCharacter
\
CharacterEscape
\
ClassSetReservedPunctuator
Let cv be the CharacterValue
of this ClassSetCharacter .
Let c be the character whose character value is cv .
Return the CharSet containing the single
character c .
ClassSetCharacter
:: \b
Return the CharSet containing the single
character U+0008 (BACKSPACE).
22.2.2.9.1 CharacterRange ( A , B )
The abstract operation CharacterRange takes arguments A (a CharSet ) and B (a CharSet ) and returns a CharSet . It performs the following steps
when called:
Assert : A and B each
contain exactly one character.
Let a be the one character in CharSet
A .
Let b be the one character in CharSet
B .
Let i be the character value of character a .
Let j be the character value of character b .
Assert : i ≤ j .
Return the CharSet containing all characters
with a character value in the inclusive
interval from i to j .
22.2.2.9.2 HasEitherUnicodeFlag ( rer )
The abstract operation HasEitherUnicodeFlag takes argument rer (a RegExp
Record ) and returns a Boolean. It performs the following steps
when called:
If rer .[[Unicode]] is
true or rer .[[UnicodeSets]] is true , then
Return true .
Return false .
22.2.2.9.3 WordCharacters ( rer )
The abstract operation WordCharacters takes argument rer (a RegExp
Record ) and returns a CharSet . Returns a
CharSet containing the characters
considered "word characters" for the purposes of \b, \B,
\w, and \W It performs the following steps when called:
Let basicWordChars be the CharSet containing
every character in the ASCII word characters .
Let extraWordChars be the CharSet containing
all characters c such that c is not in
basicWordChars but Canonicalize (rer ,
c ) is in basicWordChars .
Assert : extraWordChars is empty
unless HasEitherUnicodeFlag (rer )
is true and rer .[[IgnoreCase]] is true .
Return the union of basicWordChars and extraWordChars .
22.2.2.9.4 AllCharacters ( rer )
The abstract operation AllCharacters takes argument rer (a RegExp
Record ) and returns a CharSet . Returns the set
of “all characters” according to the regular expression flags. It performs the following
steps when called:
If rer .[[UnicodeSets]] is
true and rer .[[IgnoreCase]] is true , then
Return the CharSet
containing all Unicode code points c that do not have a Simple
Case Folding mapping (that is, scf (c )=c ).
Else if HasEitherUnicodeFlag (rer )
is true , then
Return the CharSet containing all
code point values.
Else,
Return the CharSet containing all
code unit values.
22.2.2.9.5 MaybeSimpleCaseFolding ( rer ,
A )
The abstract operation MaybeSimpleCaseFolding takes arguments rer (a RegExp
Record ) and A (a CharSet ) and returns a
CharSet . If rer .[[UnicodeSets]] is false or
rer .[[IgnoreCase]] is false , it
returns A . Otherwise, it uses the Simple Case
Folding (scf(cp ) ) definitions in the file CaseFolding.txt
of the Unicode Character Database (each of which maps a single code point to another
single code point) to map each CharSetElement of A
character-by-character into a canonical form and returns the resulting CharSet . It performs the following steps
when called:
If rer .[[UnicodeSets]] is
false or rer .[[IgnoreCase]] is false , return
A .
Let B be a new empty CharSet .
For each CharSetElement s
of A , do
Let t be an empty sequence of characters.
For each single code point cp in s , do
Append scf (cp ) to
t .
Add t to B .
Return B .
22.2.2.9.6 CharacterComplement ( rer ,
S )
The abstract operation CharacterComplement takes arguments rer (a RegExp
Record ) and S (a CharSet ) and returns a
CharSet . It performs the following steps
when called:
Let A be AllCharacters (rer ).
Return the CharSet containing the
CharSetElements of A which are not also CharSetElements of
S .
22.2.2.9.7 UnicodeMatchProperty ( rer ,
p )
The abstract operation UnicodeMatchProperty takes arguments rer (a RegExp
Record ) and p (ECMAScript source text )
and returns a Unicode property name . It performs the following
steps when called:
If rer .[[UnicodeSets]] is
true and p is a Unicode property
name listed in the “Property name ”
column of Table
71 , then
Return the List
of Unicode code points p .
Assert : p is a Unicode
property name or property alias listed in the
“Property name and aliases” column of Table 69 or
Table 70 .
Let c be the canonical property name of
p as given in the “Canonical property
name ” column of the corresponding row.
Return the List of
Unicode code points c .
Implementations must support the Unicode property names and aliases listed in Table 69 , Table 70 , and Table 71 . To
ensure interoperability, implementations must not support any other property names or
aliases.
Note 1
For example, Script_Extensions (property name ) and
scx (property alias) are valid, but script_extensions
or Scx aren't.
Note 2
The listed properties form a superset of what UTS18 RL1.2 requires.
Note 3
The spellings of entries in these tables (including casing) match the spellings
used in the file PropertyAliases.txt
in the Unicode Character Database. The precise spellings in that file are guaranteed
to be stable .
Table 69: Non-binary Unicode property aliases and their canonical
property names
Table 70: Binary Unicode property aliases and their canonical property
names
Table 71: Binary Unicode properties of strings
Property name
Basic_Emoji
Emoji_Keycap_Sequence
RGI_Emoji_Modifier_Sequence
RGI_Emoji_Flag_Sequence
RGI_Emoji_Tag_Sequence
RGI_Emoji_ZWJ_Sequence
RGI_Emoji
22.2.2.9.8 UnicodeMatchPropertyValue ( p ,
v )
The abstract operation UnicodeMatchPropertyValue takes arguments p (ECMAScript source
text ) and v (ECMAScript source text )
and returns a Unicode property value. It performs the following steps when called:
Assert : p is a canonical,
unaliased Unicode property name listed in the
“Canonical property name ” column of Table 69 .
Assert : v is a property value
or property value alias for the Unicode property p listed in PropertyValueAliases.txt .
Let value be the canonical property value of v as given in
the “Canonical property value” column of the corresponding row.
Return the List of
Unicode code points value .
Implementations must support the Unicode property values and property value aliases
listed in PropertyValueAliases.txt
for the properties listed in Table 69 .
To ensure interoperability, implementations must not support any other property values
or property value aliases.
Note 1
For example, Xpeo and Old_Persian are valid
Script_Extensions values, but xpeo and
Old Persian aren't.
Note 2
This algorithm differs from the matching
rules for symbolic values listed in UAX44 : case, white
space , U+002D (HYPHEN-MINUS), and U+005F (LOW LINE) are
not ignored, and the Is prefix is not supported.
22.2.2.10 Runtime Semantics: CompileClassSetString
The syntax-directed
operation CompileClassSetString takes argument rer (a
RegExp
Record ) and returns a sequence of characters. It is defined piecewise
over the following productions:
ClassString ::
[empty]
Return an empty sequence of characters.
ClassString ::
NonEmptyClassString
Return CompileClassSetString of
NonEmptyClassString with
argument rer .
NonEmptyClassString
::
ClassSetCharacter
NonEmptyClassString opt
Let cs be CompileToCharSet of ClassSetCharacter
with argument rer .
Let s1 be the sequence of characters that is the single CharSetElement of cs .
If NonEmptyClassString is
present, then
Let s2 be CompileClassSetString
of NonEmptyClassString
with argument rer .
Return the concatenation of s1 and s2 .
Return s1 .
22.2.3 Abstract Operations for RegExp Creation
22.2.3.1 RegExpCreate ( P , F )
The abstract operation RegExpCreate takes arguments P (an ECMAScript language value ) and
F (a String or undefined ) and returns either a normal completion
containing an Object or a throw completion . It
performs the following steps when called:
Let obj be ! RegExpAlloc (%RegExp% ).
Return ? RegExpInitialize (obj ,
P , F ).
22.2.3.2 RegExpAlloc ( newTarget )
The abstract operation RegExpAlloc takes argument newTarget (a constructor )
and returns either a normal completion
containing an Object or a throw completion . It
performs the following steps when called:
Let obj be ? OrdinaryCreateFromConstructor (newTarget ,
"%RegExp.prototype%" , « [[OriginalSource]] , [[OriginalFlags]] , [[RegExpRecord]] , [[RegExpMatcher]] »).
Perform ! DefinePropertyOrThrow (obj ,
"lastIndex" , PropertyDescriptor { [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false }).
Return obj .
22.2.3.3 RegExpInitialize ( obj , pattern ,
flags )
The abstract operation RegExpInitialize takes arguments obj (an Object),
pattern (an ECMAScript language value ), and
flags (an ECMAScript language value ) and
returns either a normal completion
containing an Object or a throw completion . It
performs the following steps when called:
If pattern is undefined , let P be the empty
String.
Else, let P be ? ToString (pattern ).
If flags is undefined , let F be the empty
String.
Else, let F be ? ToString (flags ).
If F contains any code unit other than "d" ,
"g" , "i" , "m" ,
"s" , "u" , "v" , or
"y" , or if F contains any code unit more than once,
throw a SyntaxError exception.
If F contains "i" , let i be
true ; else let i be false .
If F contains "m" , let m be
true ; else let m be false .
If F contains "s" , let s be
true ; else let s be false .
If F contains "u" , let u be
true ; else let u be false .
If F contains "v" , let v be
true ; else let v be false .
If u is true or v is
true , then
Let patternText be StringToCodePoints (P ).
Else,
Let patternText be the result of interpreting each of
P 's 16-bit elements as a Unicode BMP code point. UTF-16 decoding
is not applied to the elements.
Let parseResult be ParsePattern (patternText ,
u , v ).
If parseResult is a non-empty List of
SyntaxError objects, throw a SyntaxError
exception.
Assert :
parseResult is a Pattern Parse Node .
Set obj .[[OriginalSource]] to P .
Set obj .[[OriginalFlags]] to F .
Let capturingGroupsCount be CountLeftCapturingParensWithin (parseResult ).
Let rer be the RegExp Record { [[IgnoreCase]] : i , [[Multiline]] : m , [[DotAll]] : s , [[Unicode]] : u , [[UnicodeSets]] : v , [[CapturingGroupsCount]] :
capturingGroupsCount }.
Set obj .[[RegExpRecord]] to rer .
Set obj .[[RegExpMatcher]] to CompilePattern of
parseResult with argument rer .
Perform ? Set (obj ,
"lastIndex" , +0 𝔽 ,
true ).
Return obj .
22.2.3.4 Static Semantics: ParsePattern (
patternText , u , v )
The abstract operation ParsePattern takes arguments patternText (a sequence of
Unicode code points), u (a Boolean), and v (a Boolean) and returns a
Parse Node or a non-empty List of
SyntaxError objects.
Note
This section is amended in B.1.2.9 .
It performs the following steps when called:
If v is true and u is
true , then
Let parseResult be a List
containing one or more SyntaxError objects.
Else if v is true , then
Let parseResult be ParseText (patternText ,
Pattern [+UnicodeMode,
+UnicodeSetsMode,
+NamedCaptureGroups] ).
Else if u is true , then
Let parseResult be ParseText (patternText ,
Pattern [+UnicodeMode,
~UnicodeSetsMode,
+NamedCaptureGroups] ).
Else,
Let parseResult be ParseText (patternText ,
Pattern [~UnicodeMode,
~UnicodeSetsMode,
+NamedCaptureGroups] ).
Return parseResult .
22.2.4 The RegExp Constructor
The RegExp constructor :
is %RegExp% .
is the initial value of the "RegExp" property of the global
object .
creates and initializes a new RegExp object when called as a constructor .
when called as a function rather than as a constructor , returns either a new RegExp object,
or the argument itself if the only argument is a RegExp object.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
RegExp behaviour must include a super call to the RegExp constructor to
create and initialize subclass instances with the necessary internal slots.
22.2.4.1 RegExp ( pattern , flags )
This function performs the following steps when called:
Let patternIsRegExp be ? IsRegExp (pattern ).
If NewTarget is undefined , then
Let newTarget be the active function
object .
If patternIsRegExp is true and
flags is undefined , then
Let patternConstructor be ? Get (pattern ,
"constructor" ).
If SameValue (newTarget ,
patternConstructor ) is true , return
pattern .
Else,
Let newTarget be NewTarget.
If pattern is an Object and pattern
has a [[RegExpMatcher]] internal slot, then
Let P be pattern .[[OriginalSource]] .
If flags is undefined , let F be
pattern .[[OriginalFlags]] .
Else, let F be flags .
Else if patternIsRegExp is true , then
Let P be ? Get (pattern ,
"source" ).
If flags is undefined , then
Let F be ? Get (pattern ,
"flags" ).
Else,
Let F be flags .
Else,
Let P be pattern .
Let F be flags .
Let O be ? RegExpAlloc (newTarget ).
Return ? RegExpInitialize (O ,
P , F ).
Note
If pattern is supplied using a StringLiteral , the usual escape
sequence substitutions are performed before the String is processed by this
function. If pattern must contain an escape sequence to be recognized by this
function, any U+005C (REVERSE SOLIDUS) code points must be escaped within the
StringLiteral to
prevent them being removed when the contents of the StringLiteral are formed.
22.2.5 Properties of the RegExp Constructor
The RegExp constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
22.2.5.1 RegExp.escape ( S )
This function returns a copy of S in which characters that are potentially special
in a regular expression Pattern
have been replaced by equivalent escape sequences.
It performs the following steps when called:
If S is not a
String , throw a TypeError exception.
Let escaped be the empty String.
Let cpList be StringToCodePoints (S ).
For each code point cp of cpList , do
If escaped is the empty String and cp is matched by
either DecimalDigit or AsciiLetter ,
then
NOTE: Escaping a leading digit ensures that output corresponds with
pattern text which may be used after a \0 character
escape or a DecimalEscape such
as \1 and still match S rather than be
interpreted as an extension of the preceding escape sequence.
Escaping a leading ASCII letter does the same for the context after
\c.
Let numericValue be the numeric value of cp .
Let hex be Number::toString (𝔽 (numericValue ), 16).
Assert : The length of
hex is 2.
Set escaped to the string-concatenation
of the code unit 0x005C (REVERSE SOLIDUS), "x" ,
and hex .
Else,
Set escaped to the string-concatenation
of escaped and EncodeForRegExpEscape (cp ).
Return escaped .
Note
Despite having similar names, EscapeRegExpPattern and
RegExp.escape do not perform similar actions. The former escapes a
pattern for representation as a string, while this function escapes a string for
representation inside a pattern.
22.2.5.1.1 EncodeForRegExpEscape ( cp )
The abstract operation EncodeForRegExpEscape takes argument cp (a code point)
and returns a String. It returns a String representing a Pattern for matching cp . If
cp is white space or an ASCII punctuator, the returned value is an escape
sequence. Otherwise, the returned value is a String
representation of cp itself. It performs the following steps when called:
If cp is matched by SyntaxCharacter or
cp is U+002F (SOLIDUS), then
Return the string-concatenation
of 0x005C (REVERSE SOLIDUS) and UTF16EncodeCodePoint (cp ).
Else if cp is a code point listed in the “Code Point” column of
Table 67 ,
then
Return the string-concatenation
of 0x005C (REVERSE SOLIDUS) and the string in the “ControlEscape” column
of the row whose “Code Point” column contains cp .
Let otherPunctuators be the string-concatenation of
",-=<>#&!%:;@~'`" and the code unit 0x0022
(QUOTATION MARK).
Let toEscape be StringToCodePoints (otherPunctuators ).
If toEscape contains cp , cp is matched by
either WhiteSpace or LineTerminator ,
or cp has the same numeric value as a leading surrogate or trailing surrogate , then
Let cpNum be the numeric value of cp .
If cpNum ≤ 0xFF, then
Let hex be Number::toString (𝔽 (cpNum ), 16).
Return the string-concatenation
of the code unit 0x005C (REVERSE SOLIDUS),
"x" , and StringPad (hex ,
2, "0" , start ).
Let escaped be the empty String.
Let codeUnits be UTF16EncodeCodePoint (cp ).
For each code unit cu of codeUnits , do
Set escaped to the string-concatenation
of escaped and UnicodeEscape (cu ).
Return escaped .
Return UTF16EncodeCodePoint (cp ).
22.2.5.2 RegExp.prototype
The initial value of RegExp.prototype is the RegExp prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
22.2.5.3 get RegExp [ %Symbol.species% ]
RegExp[%Symbol.species%] is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
RegExp prototype methods normally use their this value's constructor to create a derived object.
However, a subclass constructor may over-ride that default
behaviour by redefining its %Symbol.species% property.
22.2.6 Properties of the RegExp Prototype Object
The RegExp prototype object :
is %RegExp.prototype% .
is an ordinary
object .
is not a RegExp instance and does not have a [[RegExpMatcher]]
internal slot or any of the other internal slots of RegExp instance objects.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
Note
The RegExp prototype object does not have a "valueOf" property of its
own; however, it inherits the "valueOf" property from the Object prototype
object .
22.2.6.1 RegExp.prototype.constructor
The initial value of RegExp.prototype.constructor is %RegExp% .
22.2.6.2 RegExp.prototype.exec ( string )
This method searches string for an occurrence of the regular expression pattern
and returns an Array containing the results of the match, or null if
string did not match.
It performs the following steps when called:
Let R be the this value.
Perform ? RequireInternalSlot (R ,
[[RegExpMatcher]] ).
Let S be ? ToString (string ).
Return ? RegExpBuiltinExec (R ,
S ).
22.2.6.3 get RegExp.prototype.dotAll
RegExp.prototype.dotAll is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0073 (LATIN SMALL LETTER S).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.4 get RegExp.prototype.flags
RegExp.prototype.flags is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
If R is not an Object , throw a
TypeError exception.
Let codeUnits be a new empty List .
Let hasIndices be ToBoolean (? Get (R ,
"hasIndices" )).
If hasIndices is true , append the code unit 0x0064
(LATIN SMALL LETTER D) to codeUnits .
Let global be ToBoolean (? Get (R ,
"global" )).
If global is true , append the code unit 0x0067 (LATIN
SMALL LETTER G) to codeUnits .
Let ignoreCase be ToBoolean (? Get (R ,
"ignoreCase" )).
If ignoreCase is true , append the code unit 0x0069
(LATIN SMALL LETTER I) to codeUnits .
Let multiline be ToBoolean (? Get (R ,
"multiline" )).
If multiline is true , append the code unit 0x006D
(LATIN SMALL LETTER M) to codeUnits .
Let dotAll be ToBoolean (? Get (R ,
"dotAll" )).
If dotAll is true , append the code unit 0x0073 (LATIN
SMALL LETTER S) to codeUnits .
Let unicode be ToBoolean (? Get (R ,
"unicode" )).
If unicode is true , append the code unit 0x0075 (LATIN
SMALL LETTER U) to codeUnits .
Let unicodeSets be ToBoolean (? Get (R ,
"unicodeSets" )).
If unicodeSets is true , append the code unit 0x0076
(LATIN SMALL LETTER V) to codeUnits .
Let sticky be ToBoolean (? Get (R ,
"sticky" )).
If sticky is true , append the code unit 0x0079 (LATIN
SMALL LETTER Y) to codeUnits .
Return the String value whose code units are the elements of the List
codeUnits . If codeUnits has no elements, the empty String is
returned.
22.2.6.4.1 RegExpHasFlag ( R , codeUnit
)
The abstract operation RegExpHasFlag takes arguments R (an ECMAScript language value )
and codeUnit (a code unit) and returns either a normal completion
containing either a Boolean or undefined , or a
throw
completion . It performs the following steps when called:
If R is not an Object , throw a
TypeError exception.
If R does not have an [[OriginalFlags]]
internal slot, then
If SameValue (R ,
%RegExp.prototype% )
is true , return undefined .
Otherwise, throw a TypeError exception.
Let flags be R .[[OriginalFlags]] .
If flags contains codeUnit , return
true .
Return false .
22.2.6.5 get RegExp.prototype.global
RegExp.prototype.global is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0067 (LATIN SMALL LETTER G).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.6 get RegExp.prototype.hasIndices
RegExp.prototype.hasIndices is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0064 (LATIN SMALL LETTER D).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.7 get RegExp.prototype.ignoreCase
RegExp.prototype.ignoreCase is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0069 (LATIN SMALL LETTER I).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.8 RegExp.prototype [ %Symbol.match% ] ( string
)
This method performs the following steps when called:
Let rx be the this value.
If rx is not an Object , throw a
TypeError exception.
Let S be ? ToString (string ).
Let flags be ? ToString (? Get (rx ,
"flags" )).
If flags does not contain "g" , then
Return ? RegExpExec (rx ,
S ).
Else,
If flags contains "u" or flags
contains "v" , let fullUnicode be
true ; otherwise let fullUnicode be
false .
Perform ? Set (rx ,
"lastIndex" , +0 𝔽 ,
true ).
Let A be ! ArrayCreate (0).
Let n be 0.
Repeat,
Let result be ? RegExpExec (rx ,
S ).
If result is null , then
If n = 0, return null .
Return A .
Else,
Let matchStr be ? ToString (?
Get (result ,
"0" )).
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
matchStr ).
If matchStr is the empty String, then
Let thisIndex be ℝ (?
ToLength (?
Get (rx ,
"lastIndex" ))).
Let nextIndex be AdvanceStringIndex (S ,
thisIndex , fullUnicode ).
Perform ? Set (rx ,
"lastIndex" , 𝔽 (nextIndex ),
true ).
Set n to n + 1.
The value of the "name" property of this method is
"[Symbol.match]" .
Note
The %Symbol.match% property is
used by the IsRegExp abstract operation to identify
objects that have the basic behaviour of regular expressions. The absence of a
%Symbol.match% property or the
existence of such a property whose value does not Boolean coerce to
true indicates that the object is not intended to be used as a
regular expression object.
22.2.6.9 RegExp.prototype [ %Symbol.matchAll% ] (
string )
This method performs the following steps when called:
Let R be the this value.
If R is not an Object , throw a
TypeError exception.
Let S be ? ToString (string ).
Let C be ? SpeciesConstructor (R ,
%RegExp% ).
Let flags be ? ToString (? Get (R ,
"flags" )).
Let matcher be ? Construct (C , « R ,
flags »).
Let lastIndex be ? ToLength (? Get (R ,
"lastIndex" )).
Perform ? Set (matcher ,
"lastIndex" , lastIndex , true ).
If flags contains "g" , let global be
true .
Else, let global be false .
If flags contains "u" or flags contains
"v" , let fullUnicode be true .
Else, let fullUnicode be false .
Return CreateRegExpStringIterator (matcher ,
S , global , fullUnicode ).
The value of the "name" property of this method is
"[Symbol.matchAll]" .
22.2.6.10 get RegExp.prototype.multiline
RegExp.prototype.multiline is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x006D (LATIN SMALL LETTER M).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.11 RegExp.prototype [ %Symbol.replace% ] (
string , replaceValue )
This method performs the following steps when called:
Let rx be the this value.
If rx is not an Object , throw a
TypeError exception.
Let S be ? ToString (string ).
Let lengthS be the length of S .
Let functionalReplace be IsCallable (replaceValue ).
If functionalReplace is false , then
Set replaceValue to ? ToString (replaceValue ).
Let flags be ? ToString (? Get (rx ,
"flags" )).
If flags contains "g" , let global be
true ; otherwise let global be
false .
If global is true , then
Perform ? Set (rx ,
"lastIndex" , +0 𝔽 ,
true ).
Let results be a new empty List .
Let done be false .
Repeat, while done is false ,
Let result be ? RegExpExec (rx ,
S ).
If result is null , then
Set done to true .
Else,
Append result to results .
If global is false , then
Set done to true .
Else,
Let matchStr be ? ToString (?
Get (result ,
"0" )).
If matchStr is the empty String, then
Let thisIndex be ℝ (?
ToLength (?
Get (rx ,
"lastIndex" ))).
If flags contains "u"
or flags contains "v" ,
let fullUnicode be
true ; otherwise let
fullUnicode be false .
Let nextIndex be AdvanceStringIndex (S ,
thisIndex , fullUnicode ).
Perform ? Set (rx ,
"lastIndex" , 𝔽 (nextIndex ),
true ).
Let accumulatedResult be the empty String.
Let nextSourcePosition be 0.
For each element result of results , do
Let resultLength be ? LengthOfArrayLike (result ).
Let nCaptures be max (resultLength - 1, 0).
Let matched be ? ToString (? Get (result ,
"0" )).
Let matchLength be the length of matched .
Let position be ? ToIntegerOrInfinity (? Get (result ,
"index" )).
Set position to the result of clamping
position between 0 and lengthS .
Let captures be a new empty List .
Let n be 1.
Repeat, while n ≤ nCaptures ,
Let capN be ? Get (result ,
! ToString (𝔽 (n ))).
If capN is not undefined , then
Set capN to ? ToString (capN ).
Append capN to captures .
NOTE: When n = 1, the preceding step puts the first
element into captures (at index 0). More generally, the
n th capture (the characters captured by the
n th set of capturing parentheses) is at
captures [n - 1].
Set n to n + 1.
Let namedCaptures be ? Get (result ,
"groups" ).
If functionalReplace is true , then
Let replacerArgs be the list-concatenation
of « matched », captures , and « 𝔽 (position ),
S ».
If namedCaptures is not undefined ,
then
Append namedCaptures to replacerArgs .
Let replacementValue be ? Call (replaceValue ,
undefined , replacerArgs ).
Let replacementString be ? ToString (replacementValue ).
Else,
If namedCaptures is not undefined ,
then
Set namedCaptures to ? ToObject (namedCaptures ).
Let replacementString be ? GetSubstitution (matched ,
S , position , captures ,
namedCaptures , replaceValue ).
If position ≥ nextSourcePosition , then
NOTE: position should not normally move backwards. If it
does, it is an indication of an ill-behaving RegExp subclass or use
of an access triggered side-effect to change the global flag or
other characteristics of rx . In such cases, the
corresponding substitution is ignored.
Set accumulatedResult to the string-concatenation
of accumulatedResult , the substring of
S from nextSourcePosition to
position , and replacementString .
Set nextSourcePosition to position +
matchLength .
If nextSourcePosition ≥ lengthS , return
accumulatedResult .
Return the string-concatenation of
accumulatedResult and the substring of S from
nextSourcePosition .
The value of the "name" property of this method is
"[Symbol.replace]" .
22.2.6.12 RegExp.prototype [ %Symbol.search% ] (
string )
This method performs the following steps when called:
Let rx be the this value.
If rx is not an Object , throw a
TypeError exception.
Let S be ? ToString (string ).
Let previousLastIndex be ? Get (rx ,
"lastIndex" ).
If previousLastIndex is not +0 𝔽 , then
Perform ? Set (rx ,
"lastIndex" , +0 𝔽 ,
true ).
Let result be ? RegExpExec (rx , S ).
Let currentLastIndex be ? Get (rx ,
"lastIndex" ).
If SameValue (currentLastIndex ,
previousLastIndex ) is false , then
Perform ? Set (rx ,
"lastIndex" , previousLastIndex ,
true ).
If result is null , return
-1 𝔽 .
Return ? Get (result ,
"index" ).
The value of the "name" property of this method is
"[Symbol.search]" .
Note
The "lastIndex" and "global" properties of this
RegExp object are ignored when performing the search. The
"lastIndex" property is left unchanged.
22.2.6.13 get RegExp.prototype.source
RegExp.prototype.source is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
If R is not an Object , throw a
TypeError exception.
If R does not have an [[OriginalSource]]
internal slot, then
If SameValue (R ,
%RegExp.prototype% )
is true , return "(?:)" .
Otherwise, throw a TypeError exception.
Assert :
R has an [[OriginalFlags]] internal slot.
Let src be R .[[OriginalSource]] .
Let flags be R .[[OriginalFlags]] .
Return EscapeRegExpPattern (src ,
flags ).
22.2.6.13.1 EscapeRegExpPattern ( P , F
)
The abstract operation EscapeRegExpPattern takes arguments P (a String) and
F (a String) and returns a String. It performs the following steps when
called:
If F contains "v" , then
Let patternSymbol be Pattern [+UnicodeMode,
+UnicodeSetsMode] .
Else if F contains "u" , then
Let patternSymbol be Pattern [+UnicodeMode,
~UnicodeSetsMode] .
Else,
Let patternSymbol be Pattern [~UnicodeMode,
~UnicodeSetsMode] .
Let S be a String in the form of a patternSymbol
equivalent to P interpreted as UTF-16 encoded Unicode code points
(6.1.4 ),
in which certain code points are escaped as described below. S may or
may not differ from P ; however, the Abstract Closure that would
result from evaluating S as a patternSymbol must behave
identically to the Abstract Closure given by
the constructed object's [[RegExpMatcher]] internal
slot. Multiple calls to this abstract operation using the same values for
P and F must produce identical results.
The code points / or any LineTerminator occurring in the
pattern shall be escaped in S as necessary to ensure that the
string-concatenation of
"/" , S , "/" , and F
can be parsed (in an appropriate lexical context) as a RegularExpressionLiteral
that behaves identically to the constructed regular expression. For example, if
P is "/" , then S could be
"\/" or "\u002F" , among other
possibilities, but not "/" , because /// followed
by F would be parsed as a SingleLineComment rather
than a RegularExpressionLiteral .
If P is the empty String, this specification can be met by letting
S be "(?:)" .
Return S .
Note
Despite having similar names, RegExp.escape and EscapeRegExpPattern
do not perform similar actions. The former escapes a string for representation
inside a pattern, while this function escapes a pattern for representation as a
string.
22.2.6.14 RegExp.prototype [ %Symbol.split% ] (
string , limit )
Note 1
This method returns an Array into which substrings of the result of converting
string to a String have been stored. The substrings are determined by
searching from left to right for matches of the this value
regular expression; these occurrences are not part of any String in the returned
array, but serve to divide up the String value.
The this value may be an empty regular expression or a regular
expression that can match an empty String. In this case, the regular expression does
not match the empty substring at the beginning or end of
the input String, nor does it match the empty substring
at the end of the previous separator match. (For example, if the regular expression
matches the empty String, the String is split up into individual code unit elements;
the length of the result array equals the length of the String, and each
substring contains one code unit.) Only the first match
at a given index of the String is considered, even if backtracking could yield a
non-empty substring match at that index. (For example,
/a*?/[Symbol.split]("ab") evaluates to the array
["a", "b"], while /a*/[Symbol.split]("ab") evaluates to
the array ["","b"].)
If string is (or converts to) the empty String, the result depends on
whether the regular expression can match the empty String. If it can, the result
array contains no elements. Otherwise, the result array contains one element, which
is the empty String.
If the regular expression contains capturing parentheses, then each time
separator is matched the results (including any
undefined results) of the capturing parentheses are spliced into
the output array. For example,
/<(\/)?([^<> ]+)>/[Symbol.split]("A<B > bold</B > and<CODE > coded</CODE > ")
evaluates to the array
["A" , undefined , "B" , "bold" , "/" , "B" , "and" , undefined , "CODE" , "coded" , "/" , "CODE" , "" ]
If limit is not undefined , then the output array is
truncated so that it contains no more than limit elements.
This method performs the following steps when called:
Let rx be the this value.
If rx is not an Object , throw a
TypeError exception.
Let S be ? ToString (string ).
Let C be ? SpeciesConstructor (rx ,
%RegExp% ).
Let flags be ? ToString (? Get (rx ,
"flags" )).
If flags contains "u" or flags contains
"v" , let unicodeMatching be true .
Else, let unicodeMatching be false .
If flags contains "y" , let newFlags be
flags .
Else, let newFlags be the string-concatenation of
flags and "y" .
Let splitter be ? Construct (C , « rx ,
newFlags »).
Let A be ! ArrayCreate (0).
Let lengthA be 0.
If limit is undefined , let lim be
232 - 1; else let lim be ℝ (? ToUint32 (limit )).
If lim = 0, return A .
If S is the empty String, then
Let z be ? RegExpExec (splitter ,
S ).
If z is not null , return A .
Perform ! CreateDataPropertyOrThrow (A ,
"0" , S ).
Return A .
Let size be the length of S .
Let p be 0.
Let q be p .
Repeat, while q < size ,
Perform ? Set (splitter ,
"lastIndex" , 𝔽 (q ),
true ).
Let z be ? RegExpExec (splitter ,
S ).
If z is null , then
Set q to AdvanceStringIndex (S ,
q , unicodeMatching ).
Else,
Let e be ℝ (? ToLength (? Get (splitter ,
"lastIndex" ))).
Set e to min (e ,
size ).
If e = p , then
Set q to AdvanceStringIndex (S ,
q , unicodeMatching ).
Else,
Let T be the substring of
S from p to q .
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (lengthA )),
T ).
Set lengthA to lengthA + 1.
If lengthA = lim , return A .
Set p to e .
Let numberOfCaptures be ? LengthOfArrayLike (z ).
Set numberOfCaptures to max (numberOfCaptures
- 1, 0).
Let i be 1.
Repeat, while i ≤ numberOfCaptures ,
Let nextCapture be ? Get (z ,
! ToString (𝔽 (i ))).
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (lengthA )),
nextCapture ).
Set i to i + 1.
Set lengthA to lengthA + 1.
If lengthA = lim , return
A .
Set q to p .
Let T be the substring of S from p
to size .
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (lengthA )),
T ).
Return A .
The value of the "name" property of this method is
"[Symbol.split]" .
Note 2
This method ignores the value of the "global" and
"sticky" properties of this RegExp object.
22.2.6.15 get RegExp.prototype.sticky
RegExp.prototype.sticky is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0079 (LATIN SMALL LETTER Y).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.16 RegExp.prototype.test ( S )
This method performs the following steps when called:
Let R be the this value.
If R is not an Object , throw a
TypeError exception.
Let string be ? ToString (S ).
Let match be ? RegExpExec (R ,
string ).
If match is not null , return true ;
else return false .
22.2.6.17 RegExp.prototype.toString ( )
Let R be the this value.
If R is not an Object , throw a
TypeError exception.
Let pattern be ? ToString (? Get (R ,
"source" )).
Let flags be ? ToString (? Get (R ,
"flags" )).
Let result be the string-concatenation of
"/" , pattern , "/" , and
flags .
Return result .
Note
The returned String has the form of a RegularExpressionLiteral
that evaluates to another RegExp object with the same behaviour as this object.
22.2.6.18 get RegExp.prototype.unicode
RegExp.prototype.unicode is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0075 (LATIN SMALL LETTER U).
Return ? RegExpHasFlag (R ,
cu ).
22.2.6.19 get RegExp.prototype.unicodeSets
RegExp.prototype.unicodeSets is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let R be the this value.
Let cu be the code unit 0x0076 (LATIN SMALL LETTER V).
Return ? RegExpHasFlag (R ,
cu ).
22.2.7 Abstract Operations for RegExp Matching
22.2.7.1 RegExpExec ( R , S )
The abstract operation RegExpExec takes arguments R (an Object) and S
(a String) and returns either a normal completion
containing either an Object or null , or a
throw completion . It
performs the following steps when called:
Let exec be ? Get (R ,
"exec" ).
If IsCallable (exec ) is
true , then
Let result be ? Call (exec ,
R , « S »).
If result is not an Object and
result is not null , throw a
TypeError exception.
Return result .
Perform ? RequireInternalSlot (R ,
[[RegExpMatcher]] ).
Return ? RegExpBuiltinExec (R ,
S ).
Note
If a callable "exec" property is not found this algorithm falls
back to attempting to use the built-in RegExp matching algorithm. This provides
compatible behaviour for code written for prior editions where most built-in
algorithms that use regular expressions did not perform a dynamic property lookup of
"exec" .
22.2.7.2 RegExpBuiltinExec ( R , S )
The abstract operation RegExpBuiltinExec takes arguments R (an initialized RegExp
instance) and S (a String) and returns either a normal completion
containing either an Array exotic object or
null , or a throw
completion . It performs the following steps when called:
Let length be the length of S .
Let lastIndex be ℝ (? ToLength (? Get (R ,
"lastIndex" ))).
Let flags be R .[[OriginalFlags]] .
If flags contains "g" , let global be
true ; else let global be false .
If flags contains "y" , let sticky be
true ; else let sticky be false .
If flags contains "d" , let hasIndices be
true ; else let hasIndices be false .
If global is false and sticky is
false , set lastIndex to 0.
Let matcher be R .[[RegExpMatcher]] .
If flags contains "u" or flags contains
"v" , let fullUnicode be true ; else
let fullUnicode be false .
Let matchSucceeded be false .
If fullUnicode is true , let input be
StringToCodePoints (S );
otherwise let input be a List whose
elements are the code units that are the elements of S .
NOTE: Each element of input is considered to be a character.
Repeat, while matchSucceeded is false ,
If lastIndex > length , then
If global is true or sticky
is true , then
Perform ? Set (R ,
"lastIndex" ,
+0 𝔽 ,
true ).
Return null .
Let inputIndex be the index into input of the
character that was obtained from element lastIndex of
S .
Let r be matcher (input ,
inputIndex ).
If r is failure , then
If sticky is true , then
Perform ? Set (R ,
"lastIndex" ,
+0 𝔽 ,
true ).
Return null .
Set lastIndex to AdvanceStringIndex (S ,
lastIndex , fullUnicode ).
Else,
Assert : r is a
MatchState .
Set matchSucceeded to true .
Let e be r .[[EndIndex]] .
If fullUnicode is true , set e to GetStringIndex (S ,
e ).
If global is true or sticky is
true , then
Perform ? Set (R ,
"lastIndex" , 𝔽 (e ),
true ).
Let n be the number of elements in r .[[Captures]] .
Assert :
n = R .[[RegExpRecord]] .[[CapturingGroupsCount]] .
Assert :
n < 232 - 1.
Let A be ! ArrayCreate (n + 1).
Assert :
The mathematical value of
A 's "length" property is n + 1.
Perform ! CreateDataPropertyOrThrow (A ,
"index" , 𝔽 (lastIndex )).
Perform ! CreateDataPropertyOrThrow (A ,
"input" , S ).
Let match be the Match Record { [[StartIndex]] : lastIndex , [[EndIndex]] : e }.
Let indices be a new empty List .
Let groupNames be a new empty List .
Append match to indices .
Let matchedSubstr be GetMatchString (S ,
match ).
Perform ! CreateDataPropertyOrThrow (A ,
"0" , matchedSubstr ).
If R contains any GroupName , then
Let groups be OrdinaryObjectCreate (null ).
Let hasGroups be true .
Else,
Let groups be undefined .
Let hasGroups be false .
Perform ! CreateDataPropertyOrThrow (A ,
"groups" , groups ).
Let matchedGroupNames be a new empty List .
For each integer i such that 1 ≤
i ≤ n , in ascending order, do
Let captureI be i th element of
r .[[Captures]] .
If captureI is undefined , then
Let capturedValue be undefined .
Append undefined to indices .
Else,
Let captureStart be captureI .[[StartIndex]] .
Let captureEnd be captureI .[[EndIndex]] .
If fullUnicode is true , then
Set captureStart to GetStringIndex (S ,
captureStart ).
Set captureEnd to GetStringIndex (S ,
captureEnd ).
Let capture be the Match
Record { [[StartIndex]] : captureStart ,
[[EndIndex]] : captureEnd }.
Let capturedValue be GetMatchString (S ,
capture ).
Append capture to indices .
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (i )),
capturedValue ).
If the i th capture of R was defined with a
GroupName ,
then
Let s be the CapturingGroupName
of that GroupName .
If matchedGroupNames contains s , then
Assert :
capturedValue is undefined .
Append undefined to
groupNames .
Else,
If capturedValue is not
undefined , append s to
matchedGroupNames .
NOTE: If there are multiple groups named s ,
groups may already have an s property
at this point. However, because groups is an
ordinary
object whose properties are all
writable data
properties , the call to CreateDataPropertyOrThrow
is nevertheless guaranteed to succeed.
Perform ! CreateDataPropertyOrThrow (groups ,
s , capturedValue ).
Append s to groupNames .
Else,
Append undefined to groupNames .
If hasIndices is true , then
Let indicesArray be MakeMatchIndicesIndexPairArray (S ,
indices , groupNames , hasGroups ).
Perform ! CreateDataPropertyOrThrow (A ,
"indices" , indicesArray ).
Return A .
22.2.7.3 AdvanceStringIndex ( S , index ,
unicode )
The abstract operation AdvanceStringIndex takes arguments S (a String),
index (a non-negative integer ), and unicode (a Boolean) and
returns an integer . It performs the following steps when called:
Assert :
index ≤ 253 - 1.
If unicode is false , return index + 1.
Let length be the length of S .
If index + 1 ≥ length , return index + 1.
Let cp be CodePointAt (S ,
index ).
Return index + cp .[[CodeUnitCount]] .
22.2.7.4 GetStringIndex ( S ,
codePointIndex )
The abstract operation GetStringIndex takes arguments S (a String) and
codePointIndex (a non-negative integer ) and returns a non-negative integer . It interprets
S as a sequence of UTF-16 encoded code points, as described in 6.1.4 , and returns
the code unit index corresponding to code point index codePointIndex when such an
index exists. Otherwise, it returns the length of S . It performs the following
steps when called:
If S is the empty String, return 0.
Let len be the length of S .
Let codeUnitCount be 0.
Let codePointCount be 0.
Repeat, while codeUnitCount < len ,
If codePointCount = codePointIndex , return
codeUnitCount .
Let cp be CodePointAt (S ,
codeUnitCount ).
Set codeUnitCount to codeUnitCount +
cp .[[CodeUnitCount]] .
Set codePointCount to codePointCount + 1.
Return len .
22.2.7.5 Match Records
A Match Record is a Record value used to
encapsulate the start and end indices of a regular expression match or capture.
Match Records have the fields listed in Table 72 .
Table 72: Match Record Fields
Field Name
Value
Meaning
[[StartIndex]]
a non-negative integer
The number of code units from the start of a string at which the match
begins (inclusive).
[[EndIndex]]
an integer ≥ [[StartIndex]]
The number of code units from the start of a string at which the match
ends (exclusive).
22.2.7.6 GetMatchString ( S , match )
The abstract operation GetMatchString takes arguments S (a String) and
match (a Match Record ) and returns a String. It
performs the following steps when called:
Assert :
match .[[StartIndex]] ≤ match .[[EndIndex]] ≤ the length of S .
Return the substring of S from
match .[[StartIndex]] to match .[[EndIndex]] .
22.2.7.7 GetMatchIndexPair ( S , match )
The abstract operation GetMatchIndexPair takes arguments S (a String) and
match (a Match Record ) and returns an Array. It
performs the following steps when called:
Assert :
match .[[StartIndex]] ≤ match .[[EndIndex]] ≤ the length of S .
Return CreateArrayFromList («
𝔽 (match .[[StartIndex]] ), 𝔽 (match .[[EndIndex]] ) »).
22.2.7.8 MakeMatchIndicesIndexPairArray ( S ,
indices , groupNames , hasGroups )
The abstract operation MakeMatchIndicesIndexPairArray takes arguments S (a
String), indices (a List of
either Match Records or
undefined ), groupNames (a List of either Strings
or undefined ), and hasGroups (a Boolean) and returns an Array.
It performs the following steps when called:
Let n be the number of elements in indices .
Assert :
n < 232 - 1.
Assert :
groupNames has n - 1 elements.
NOTE: The groupNames List contains
elements aligned with the indices List starting
at indices [1].
Let A be ! ArrayCreate (n ).
If hasGroups is true , then
Let groups be OrdinaryObjectCreate (null ).
Else,
Let groups be undefined .
Perform ! CreateDataPropertyOrThrow (A ,
"groups" , groups ).
For each integer i such that 0 ≤
i < n , in ascending order, do
Let matchIndices be indices [i ].
If matchIndices is not undefined , then
Let matchIndexPair be GetMatchIndexPair (S ,
matchIndices ).
Else,
Let matchIndexPair be undefined .
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (i )),
matchIndexPair ).
If i > 0, then
Let s be groupNames [i - 1].
If s is not undefined , then
Assert :
groups is not undefined .
NOTE: If there are multiple groups named s ,
groups may already have an s property
at this point. However, because groups is an
ordinary
object whose properties are all
writable data
properties , the call to CreateDataPropertyOrThrow
is nevertheless guaranteed to succeed.
Perform ! CreateDataPropertyOrThrow (groups ,
s , matchIndexPair ).
Return A .
22.2.8 Properties of RegExp Instances
RegExp instances are ordinary objects that inherit properties from the
RegExp prototype
object . RegExp instances have internal slots [[OriginalSource]] , [[OriginalFlags]] , [[RegExpRecord]] , and [[RegExpMatcher]] . The
value of the [[RegExpMatcher]] internal slot is an Abstract
Closure representation of the Pattern of the RegExp object.
Note
Prior to ECMAScript 2015, RegExp instances were specified as having the own data
properties "source" ,
"global" , "ignoreCase" , and
"multiline" . Those properties are now specified as accessor
properties of RegExp.prototype.
RegExp instances also have the following property:
22.2.8.1 lastIndex
The value of the "lastIndex" property specifies the String index at which
to start the next match. It is coerced to an integral Number when used (see
22.2.7.2 ). This property shall have the
attributes { [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false }.
22.2.9 RegExp String Iterator Objects
A RegExp String Iterator is an object that represents a specific iteration
over some specific String instance object, matching against some specific RegExp instance
object. There is not a named constructor for RegExp String Iterator objects.
Instead, RegExp String Iterator objects are created by calling certain methods of RegExp
instance objects.
22.2.9.1 CreateRegExpStringIterator ( R ,
S , global , fullUnicode )
The abstract operation CreateRegExpStringIterator takes arguments R (an Object),
S (a String), global (a Boolean), and fullUnicode (a
Boolean) and returns an Object. It performs the following steps when called:
Let iterator be OrdinaryObjectCreate (%RegExpStringIteratorPrototype% ,
« [[IteratingRegExp]] , [[IteratedString]] , [[Global]] ,
[[Unicode]] , [[Done]] »).
Set iterator .[[IteratingRegExp]] to
R .
Set iterator .[[IteratedString]] to S .
Set iterator .[[Global]] to global .
Set iterator .[[Unicode]] to
fullUnicode .
Set iterator .[[Done]] to
false .
Return iterator .
22.2.9.2 The %RegExpStringIteratorPrototype% Object
The %RegExpStringIteratorPrototype% object:
22.2.9.2.1 %RegExpStringIteratorPrototype%.next ( )
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
If O does not have all of the internal slots of a RegExp String
Iterator Object Instance (see 22.2.9.3 ),
throw a TypeError exception.
If O .[[Done]] is true ,
then
Return CreateIteratorResultObject (undefined ,
true ).
Let R be O .[[IteratingRegExp]] .
Let S be O .[[IteratedString]] .
Let global be O .[[Global]] .
Let fullUnicode be O .[[Unicode]] .
Let match be ? RegExpExec (R ,
S ).
If match is null , then
Set O .[[Done]] to
true .
Return CreateIteratorResultObject (undefined ,
true ).
If global is false , then
Set O .[[Done]] to
true .
Return CreateIteratorResultObject (match ,
false ).
Let matchStr be ? ToString (?
Get (match ,
"0" )).
If matchStr is the empty String, then
Let thisIndex be ℝ (? ToLength (? Get (R ,
"lastIndex" ))).
Let nextIndex be AdvanceStringIndex (S ,
thisIndex , fullUnicode ).
Perform ? Set (R ,
"lastIndex" , 𝔽 (nextIndex ),
true ).
Return CreateIteratorResultObject (match ,
false ).
22.2.9.2.2 %RegExpStringIteratorPrototype% [
%Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is
the String value "RegExp String Iterator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
22.2.9.3 Properties of RegExp String Iterator Instances
RegExp String Iterator
instances are ordinary objects that inherit properties from
the %RegExpStringIteratorPrototype%
intrinsic object. RegExp String Iterator
instances are initially created with the internal slots listed in Table 73 .
Table 73: Internal Slots of RegExp String
Iterator Instances
Internal Slot
Type
Description
[[IteratingRegExp]]
an Object
The regular expression used for iteration. IsRegExp ([[IteratingRegExp]] ) is initially
true .
[[IteratedString]]
a String
The String value being iterated upon.
[[Global]]
a Boolean
Indicates whether the [[IteratingRegExp]] is
global or not.
[[Unicode]]
a Boolean
Indicates whether the [[IteratingRegExp]] is in
Unicode mode or not.
[[Done]]
a Boolean
Indicates whether the iteration is complete or not.
23 Indexed Collections
23.1 Array Objects
Arrays are exotic
objects that give special treatment to a certain class of property names. See
10.4.2 for a definition of this special
treatment.
23.1.1 The Array Constructor
The Array constructor :
is %Array% .
is the initial value of the "Array" property of the global
object .
creates and initializes a new Array when called as a constructor .
also creates and initializes a new Array when called as a function rather than as a
constructor . Thus the function call
Array(…) is equivalent to the object creation expression
new Array(…) with the same arguments.
is a function whose behaviour differs based upon the number and types of its arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the exotic
Array behaviour must include a super call to the Array constructor to
initialize subclass instances that are Array exotic objects .
However, most of the Array.prototype methods are generic methods that are not
dependent upon their this value being an Array exotic
object .
23.1.1.1 Array ( ...values )
This function performs the following steps when called:
If NewTarget is undefined , let newTarget be the
active function object ; else
let newTarget be NewTarget.
Let proto be ? GetPrototypeFromConstructor (newTarget ,
"%Array.prototype%" ).
Let numberOfArgs be the number of elements in values .
If numberOfArgs = 0, then
Return ! ArrayCreate (0,
proto ).
Else if numberOfArgs = 1, then
Let len be values [0].
Let array be ! ArrayCreate (0,
proto ).
If len is not a
Number , then
Perform ! CreateDataPropertyOrThrow (array ,
"0" , len ).
Let intLen be 1 𝔽 .
Else,
Let intLen be ! ToUint32 (len ).
If SameValueZero (intLen ,
len ) is false , throw a
RangeError exception.
Perform ! Set (array ,
"length" , intLen , true ).
Return array .
Else,
Assert : numberOfArgs ≥ 2.
Let array be ? ArrayCreate (numberOfArgs ,
proto ).
Let k be 0.
Repeat, while k < numberOfArgs ,
Let Pk be ! ToString (𝔽 (k )).
Let itemK be values [k ].
Perform ! CreateDataPropertyOrThrow (array ,
Pk , itemK ).
Set k to k + 1.
Assert : The mathematical value of
array 's "length" property is
numberOfArgs .
Return array .
23.1.2 Properties of the Array Constructor
The Array constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has a "length" property whose value is 1 𝔽 .
has the following properties:
23.1.2.1 Array.from ( items [ , mapper [ ,
thisArg ] ] )
This method performs the following steps when called:
Let C be the this value.
If mapper is undefined , then
Let mapping be false .
Else,
If IsCallable (mapper )
is false , throw a TypeError exception.
Let mapping be true .
Let usingIterator be ? GetMethod (items , %Symbol.iterator% ).
If usingIterator is not undefined , then
If IsConstructor (C )
is true , then
Let A be ? Construct (C ).
Else,
Let A be ! ArrayCreate (0).
Let iteratorRecord be ? GetIteratorFromMethod (items ,
usingIterator ).
Let k be 0.
Repeat,
If k ≥ 253 - 1, then
Let error be ThrowCompletion (a
newly created TypeError object).
Return ? IteratorClose (iteratorRecord ,
error ).
Let Pk be ! ToString (𝔽 (k )).
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , then
Perform ? Set (A ,
"length" , 𝔽 (k ),
true ).
Return A .
If mapping is true , then
Let mappedValue be Completion (Call (mapper ,
thisArg , « next , 𝔽 (k ) »)).
IfAbruptCloseIterator (mappedValue ,
iteratorRecord ).
Else,
Let mappedValue be next .
Let defineStatus be Completion (CreateDataPropertyOrThrow (A ,
Pk , mappedValue )).
IfAbruptCloseIterator (defineStatus ,
iteratorRecord ).
Set k to k + 1.
NOTE: items is not iterable so
assume it is an array-like object .
Let arrayLike be ! ToObject (items ).
Let len be ? LengthOfArrayLike (arrayLike ).
If IsConstructor (C ) is
true , then
Let A be ? Construct (C , «
𝔽 (len ) »).
Else,
Let A be ? ArrayCreate (len ).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ? Get (arrayLike ,
Pk ).
If mapping is true , then
Let mappedValue be ? Call (mapper ,
thisArg , « kValue , 𝔽 (k ) »).
Else,
Let mappedValue be kValue .
Perform ? CreateDataPropertyOrThrow (A ,
Pk , mappedValue ).
Set k to k + 1.
Perform ? Set (A ,
"length" , 𝔽 (len ), true ).
Return A .
Note
This method is an intentionally generic factory method; it does not require that its
this value be the Array constructor . Therefore it
can be transferred to or inherited by any other constructors that may be
called with a single numeric argument.
23.1.2.2 Array.isArray ( arg )
This function performs the following steps when called:
Return ? IsArray (arg ).
23.1.2.3 Array.of ( ...items )
This method performs the following steps when called:
Let len be the number of elements in items .
Let lenNumber be 𝔽 (len ).
Let C be the this value.
If IsConstructor (C ) is
true , then
Let A be ? Construct (C , «
lenNumber »).
Else,
Let A be ? ArrayCreate (len ).
Let k be 0.
Repeat, while k < len ,
Let kValue be items [k ].
Let Pk be ! ToString (𝔽 (k )).
Perform ? CreateDataPropertyOrThrow (A ,
Pk , kValue ).
Set k to k + 1.
Perform ? Set (A ,
"length" , lenNumber , true ).
Return A .
Note
This method is an intentionally generic factory method; it does not require that its
this value be the Array constructor . Therefore it
can be transferred to or inherited by other constructors that may be
called with a single numeric argument.
23.1.2.4 Array.prototype
The value of Array.prototype is the Array prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
23.1.2.5 get Array [ %Symbol.species% ]
Array[%Symbol.species%] is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
Array prototype methods normally use their this value's constructor to create a derived object.
However, a subclass constructor may over-ride that default
behaviour by redefining its %Symbol.species% property.
23.1.3 Properties of the Array Prototype Object
The Array prototype object :
is %Array.prototype% .
is an Array exotic object and has the internal
methods specified for such objects.
has a "length" property whose initial value is
+0 𝔽 and whose attributes are { [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false }.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
Note
The Array prototype object is specified to be an Array exotic object to
ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015
specification.
23.1.3.1 Array.prototype.at ( index )
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeIndex be ? ToIntegerOrInfinity (index ).
If relativeIndex ≥ 0, then
Let k be relativeIndex .
Else,
Let k be len + relativeIndex .
If k < 0 or k ≥ len , return
undefined .
Return ? Get (O , ! ToString (𝔽 (k ))).
23.1.3.2 Array.prototype.concat ( ...items )
This method returns an array containing the array elements of the object followed by the
array elements of each argument.
It performs the following steps when called:
Let O be ? ToObject (this value).
Let A be ? ArraySpeciesCreate (O , 0).
Let n be 0.
Prepend O to items .
For each element E of items , do
Let spreadable be ? IsConcatSpreadable (E ).
If spreadable is true , then
Let len be ? LengthOfArrayLike (E ).
If n + len > 253 - 1, throw a
TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let exists be ? HasProperty (E ,
Pk ).
If exists is true , then
Let subElement be ? Get (E ,
Pk ).
Perform ? CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
subElement ).
Set n to n + 1.
Set k to k + 1.
Else,
NOTE: E is added as a single item rather than spread.
If n ≥ 253 - 1, throw a
TypeError exception.
Perform ? CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )), E ).
Set n to n + 1.
Perform ? Set (A ,
"length" , 𝔽 (n ), true ).
Return A .
The "length" property of this method is 1 𝔽 .
Note 1
The explicit setting of the "length" property in step 6 is intended to
ensure the length is correct when the final non-empty element of items
has trailing holes or when A is not a built-in Array.
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.2.1 IsConcatSpreadable ( O )
The abstract operation IsConcatSpreadable takes argument O (an ECMAScript language value )
and returns either a normal
completion containing a Boolean or a throw
completion . It performs the following steps when called:
If O is not an Object , return
false .
Let spreadable be ? Get (O ,
%Symbol.isConcatSpreadable% ).
If spreadable is not undefined , return ToBoolean (spreadable ).
Return ? IsArray (O ).
23.1.3.3 Array.prototype.constructor
The initial value of Array.prototype.constructor is %Array% .
23.1.3.4 Array.prototype.copyWithin ( target ,
start [ , end ] )
Note 1
The end argument is optional. If it is not provided, the length of the
this value is used.
Note 2
If target is negative, it is treated as length + target where
length is the length of the array. If start is negative, it is
treated as length + start .
If end is negative, it is treated as length + end .
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeTarget be ? ToIntegerOrInfinity (target ).
If relativeTarget = -∞, let to be 0.
Else if relativeTarget < 0, let to be max (len +
relativeTarget , 0).
Else, let to be min (relativeTarget ,
len ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let from be 0.
Else if relativeStart < 0, let from be max (len +
relativeStart , 0).
Else, let from be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let final be 0.
Else if relativeEnd < 0, let final be max (len +
relativeEnd , 0).
Else, let final be min (relativeEnd , len ).
Let count be min (final - from ,
len - to ).
If from < to and to < from +
count , then
Let direction be -1.
Set from to from + count - 1.
Set to to to + count - 1.
Else,
Let direction be 1.
Repeat, while count > 0,
Let fromKey be ! ToString (𝔽 (from )).
Let toKey be ! ToString (𝔽 (to )).
Let fromPresent be ? HasProperty (O ,
fromKey ).
If fromPresent is true , then
Let fromValue be ? Get (O ,
fromKey ).
Perform ? Set (O ,
toKey , fromValue , true ).
Else,
Assert : fromPresent
is false .
Perform ? DeletePropertyOrThrow (O ,
toKey ).
Set from to from + direction .
Set to to to + direction .
Set count to count - 1.
Return O .
Note 3
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.5 Array.prototype.entries ( )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Return CreateArrayIterator (O ,
key+value ).
23.1.3.6 Array.prototype.every ( callback [ ,
thisArg ] )
Note 1
callback should be a function that accepts three arguments and returns a
value that is coercible to a Boolean value. every calls
callback once for each element present in the array, in ascending order,
until it finds one where callback returns false . If
such an element is found, every immediately returns
false . Otherwise, every returns
true . callback is called only for elements of the
array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the element, the
index of the element, and the object being traversed.
every does not directly mutate the object on which it is called but the
object may be mutated by the calls to callback .
The range of elements processed by every is set before the first call to
callback . Elements which are appended to the array after the call to
every begins will not be visited by callback . If existing
elements of the array are changed, their value as passed to callback will
be the value at the time every visits them; elements that are deleted
after the call to every begins and before being visited are not
visited. every acts like the "for all" quantifier in mathematics. In
particular, for an empty array, it returns true .
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Let testResult be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If testResult is false , return
false .
Set k to k + 1.
Return true .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.7 Array.prototype.fill ( value [ ,
start [ , end ] ] )
Note 1
The start argument is optional. If it is not provided,
+0 𝔽 is used.
The end argument is optional. If it is not provided, the length of the
this value is used.
Note 2
If start is negative, it is treated as length + start where
length is the length of the array. If end is negative, it is
treated as length + end .
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let k be 0.
Else if relativeStart < 0, let k be max (len +
relativeStart , 0).
Else, let k be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let final be 0.
Else if relativeEnd < 0, let final be max (len +
relativeEnd , 0).
Else, let final be min (relativeEnd , len ).
Repeat, while k < final ,
Let Pk be ! ToString (𝔽 (k )).
Perform ? Set (O , Pk ,
value , true ).
Set k to k + 1.
Return O .
Note 3
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.8 Array.prototype.filter ( callback [ ,
thisArg ] )
Note 1
callback should be a function that accepts three arguments and returns a
value that is coercible to a Boolean value. filter calls
callback once for each element in the array, in ascending order, and
constructs a new array of all the values for which callback returns
true . callback is called only for elements of the
array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the element, the
index of the element, and the object being traversed.
filter does not directly mutate the object on which it is called but the
object may be mutated by the calls to callback .
The range of elements processed by filter is set before the first call
to callback . Elements which are appended to the array after the call to
filter begins will not be visited by callback . If existing
elements of the array are changed their value as passed to callback will
be the value at the time filter visits them; elements that are deleted
after the call to filter begins and before being visited are not
visited.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let A be ? ArraySpeciesCreate (O , 0).
Let k be 0.
Let to be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Let selected be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If selected is true , then
Perform ? CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (to )),
kValue ).
Set to to to + 1.
Set k to k + 1.
Return A .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.9 Array.prototype.find ( predicate [ ,
thisArg ] )
Note 1
This method calls predicate once for each element of the array, in
ascending index order, until it finds one where predicate returns a value
that coerces to true . If such an element is found,
find immediately returns that element value. Otherwise,
find returns undefined .
See FindViaPredicate for additional
information.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let findRec be ? FindViaPredicate (O ,
len , ascending , predicate ,
thisArg ).
Return findRec .[[Value]] .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.10 Array.prototype.findIndex ( predicate [ ,
thisArg ] )
Note 1
This method calls predicate once for each element of the array, in
ascending index order, until it finds one where predicate returns a value
that coerces to true . If such an element is found,
findIndex immediately returns the index of that element value.
Otherwise, findIndex returns -1.
See FindViaPredicate for additional
information.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let findRec be ? FindViaPredicate (O ,
len , ascending , predicate ,
thisArg ).
Return findRec .[[Index]] .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.11 Array.prototype.findLast ( predicate [ ,
thisArg ] )
Note 1
This method calls predicate once for each element of the array, in
descending index order, until it finds one where predicate returns a
value that coerces to true . If such an element is found,
findLast immediately returns that element value. Otherwise,
findLast returns undefined .
See FindViaPredicate for additional
information.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let findRec be ? FindViaPredicate (O ,
len , descending , predicate ,
thisArg ).
Return findRec .[[Value]] .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array object. Therefore it can be transferred to
other kinds of objects for use as a method.
23.1.3.12 Array.prototype.findLastIndex ( predicate [
, thisArg ] )
Note 1
This method calls predicate once for each element of the array, in
descending index order, until it finds one where predicate returns a
value that coerces to true . If such an element is found,
findLastIndex immediately returns the index of that element value.
Otherwise, findLastIndex returns -1.
See FindViaPredicate for additional
information.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let findRec be ? FindViaPredicate (O ,
len , descending , predicate ,
thisArg ).
Return findRec .[[Index]] .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array object. Therefore it can be transferred to
other kinds of objects for use as a method.
23.1.3.12.1 FindViaPredicate ( O , len ,
direction , predicate , thisArg )
The abstract operation FindViaPredicate takes arguments O (an Object),
len (a non-negative integer ), direction
(ascending or descending ),
predicate (an ECMAScript language
value ), and thisArg (an ECMAScript language value )
and returns either a normal
completion containing a Record with fields
[[Index]] (an integral Number ) and [[Value]] (an ECMAScript language
value ) or a throw
completion .
O should be an array-like object or a TypedArray .
This operation calls predicate once for each element of O , in
either ascending index order or descending index order (as indicated by
direction ), until it finds one where predicate returns a value
that coerces to true . At that point, this operation returns a
Record that gives
the index and value of the element found. If no such element is found, this operation
returns a Record that
specifies -1 𝔽 for the index and
undefined for the value.
predicate should be a function. When called for an element of the array, it is
passed three arguments: the value of the element, the index of the element, and the
object being traversed. Its return value will be coerced to a Boolean value.
thisArg will be used as the this value for each invocation
of predicate .
This operation does not directly mutate the object on which it is called, but the object
may be mutated by the calls to predicate .
The range of elements processed is set before the first call to predicate ,
just before the traversal begins. Elements that are appended to the array after this
will not be visited by predicate . If existing elements of the array are
changed, their value as passed to predicate will be the value at the time
that this operation visits them. Elements that are deleted after traversal begins and
before being visited are still visited and are either looked up from the prototype or
are undefined .
It performs the following steps when called:
If IsCallable (predicate )
is false , throw a TypeError exception.
If direction is ascending , then
Let indices be a List
of the integers in the interval from 0 (inclusive) to
len (exclusive), in ascending order.
Else,
Let indices be a List
of the integers in the interval from 0 (inclusive) to
len (exclusive), in descending order.
For each integer k of
indices , do
Let Pk be ! ToString (𝔽 (k )).
NOTE: If O is a TypedArray , the
following invocation of Get will return a normal
completion .
Let kValue be ? Get (O ,
Pk ).
Let testResult be ? Call (predicate ,
thisArg , « kValue , 𝔽 (k ),
O »).
If ToBoolean (testResult )
is true , return the Record
{ [[Index]] : 𝔽 (k ), [[Value]] : kValue }.
Return the Record {
[[Index]] : -1 𝔽 , [[Value]] : undefined }.
23.1.3.13 Array.prototype.flat ( [ depth ] )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let sourceLen be ? LengthOfArrayLike (O ).
Let depthNum be 1.
If depth is not undefined , then
Set depthNum to ? ToIntegerOrInfinity (depth ).
If depthNum < 0, set depthNum to 0.
Let A be ? ArraySpeciesCreate (O , 0).
Perform ? FlattenIntoArray (A ,
O , sourceLen , 0, depthNum ).
Return A .
23.1.3.13.1 FlattenIntoArray ( target ,
source , sourceLen , start , depth [ ,
mapperFunction [ , thisArg ] ] )
The abstract operation FlattenIntoArray takes arguments target (an Object),
source (an Object), sourceLen (a non-negative integer ),
start (a non-negative integer ), and depth (a non-negative
integer or
+∞) and optional arguments mapperFunction (a function
object ) and thisArg (an ECMAScript language value )
and returns either a normal
completion containing a non-negative integer or a throw
completion . It performs the following steps when called:
Assert : If mapperFunction is
present, then IsCallable (mapperFunction )
is true , thisArg is present, and depth
is 1.
Let targetIndex be start .
Let sourceIndex be +0 𝔽 .
Repeat, while ℝ (sourceIndex ) <
sourceLen ,
Let P be ! ToString (sourceIndex ).
Let exists be ? HasProperty (source ,
P ).
If exists is true , then
Let element be ? Get (source ,
P ).
If mapperFunction is present, then
Set element to ? Call (mapperFunction ,
thisArg , « element ,
sourceIndex , source »).
Let shouldFlatten be false .
If depth > 0, then
Set shouldFlatten to ? IsArray (element ).
If shouldFlatten is true , then
If depth = +∞, let newDepth be +∞.
Else, let newDepth be depth - 1.
Let elementLen be ? LengthOfArrayLike (element ).
Set targetIndex to ? FlattenIntoArray (target ,
element , elementLen ,
targetIndex , newDepth ).
Else,
If targetIndex ≥ 253 - 1, throw a
TypeError exception.
Perform ? CreateDataPropertyOrThrow (target ,
! ToString (𝔽 (targetIndex )),
element ).
Set targetIndex to targetIndex +
1.
Set sourceIndex to sourceIndex +
1 𝔽 .
Return targetIndex .
23.1.3.14 Array.prototype.flatMap ( mapperFunction [
, thisArg ] )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let sourceLen be ? LengthOfArrayLike (O ).
If IsCallable (mapperFunction )
is false , throw a TypeError exception.
Let A be ? ArraySpeciesCreate (O , 0).
Perform ? FlattenIntoArray (A ,
O , sourceLen , 0, 1, mapperFunction ,
thisArg ).
Return A .
23.1.3.15 Array.prototype.forEach ( callback [ ,
thisArg ] )
Note 1
callback should be a function that accepts three arguments.
forEach calls callback once for each element present in the
array, in ascending order. callback is called only for elements of the
array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the element, the
index of the element, and the object being traversed.
forEach does not directly mutate the object on which it is called but
the object may be mutated by the calls to callback .
The range of elements processed by forEach is set before the first call
to callback . Elements which are appended to the array after the call to
forEach begins will not be visited by callback . If existing
elements of the array are changed, their value as passed to callback will
be the value at the time forEach visits them; elements that are deleted
after the call to forEach begins and before being visited are not
visited.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Perform ? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »).
Set k to k + 1.
Return undefined .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.16 Array.prototype.includes ( searchElement [
, fromIndex ] )
Note 1
This method compares searchElement to the elements of the array, in
ascending order, using the SameValueZero algorithm, and if
found at any position, returns true ; otherwise, it returns
false .
The optional second argument fromIndex defaults to
+0 𝔽 (i.e. the whole array is searched). If it is
greater than or equal to the length of the array, false is
returned, i.e. the array will not be searched. If it is less than
-0 𝔽 , it is used as the offset from the end of the
array to compute fromIndex . If the computed index is less than or equal
to +0 𝔽 , the whole array will be searched.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If len = 0, return false .
Let n be ? ToIntegerOrInfinity (fromIndex ).
Assert : If
fromIndex is undefined , then n is 0.
If n = +∞, return false .
Else if n = -∞, set n to 0.
If n ≥ 0, then
Let k be n .
Else,
Let k be len + n .
If k < 0, set k to 0.
Repeat, while k < len ,
Let elementK be ? Get (O ,
! ToString (𝔽 (k ))).
If SameValueZero (searchElement ,
elementK ) is true , return
true .
Set k to k + 1.
Return false .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
Note 3
This method intentionally differs from the similar indexOf method in two
ways. First, it uses the SameValueZero algorithm, instead of
IsStrictlyEqual , allowing it to
detect NaN array elements. Second, it does not skip missing array
elements, instead treating them as undefined .
23.1.3.17 Array.prototype.indexOf ( searchElement [ ,
fromIndex ] )
This method compares searchElement to the elements of the array, in ascending
order, using the IsStrictlyEqual algorithm, and if found
at one or more indices, returns the smallest such index; otherwise, it returns
-1 𝔽 .
Note 1
The optional second argument fromIndex defaults to
+0 𝔽 (i.e. the whole array is searched). If it is
greater than or equal to the length of the array, -1 𝔽
is returned, i.e. the array will not be searched. If it is less than
-0 𝔽 , it is used as the offset from the end of the
array to compute fromIndex . If the computed index is less than or equal
to +0 𝔽 , the whole array will be searched.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If len = 0, return -1 𝔽 .
Let n be ? ToIntegerOrInfinity (fromIndex ).
Assert : If
fromIndex is undefined , then n is 0.
If n = +∞, return -1 𝔽 .
Else if n = -∞, set n to 0.
If n ≥ 0, then
Let k be n .
Else,
Let k be len + n .
If k < 0, set k to 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let elementK be ? Get (O ,
Pk ).
If IsStrictlyEqual (searchElement ,
elementK ) is true , return 𝔽 (k ).
Set k to k + 1.
Return -1 𝔽 .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.18 Array.prototype.join ( separator )
This method converts the elements of the array to Strings, and then concatenates these
Strings, separated by occurrences of the separator . If no separator is provided,
a single comma is used as the separator.
It performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If separator is undefined , let sep be
"," .
Else, let sep be ? ToString (separator ).
Let R be the empty String.
Let k be 0.
Repeat, while k < len ,
If k > 0, set R to the string-concatenation of
R and sep .
Let element be ? Get (O ,
! ToString (𝔽 (k ))).
If element is neither undefined nor
null , then
Let S be ? ToString (element ).
Set R to the string-concatenation
of R and S .
Set k to k + 1.
Return R .
Note
This method is intentionally generic; it does not require that its
this value be an Array. Therefore, it can be transferred to other
kinds of objects for use as a method.
23.1.3.19 Array.prototype.keys ( )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Return CreateArrayIterator (O ,
key ).
23.1.3.20 Array.prototype.lastIndexOf ( searchElement
[ , fromIndex ] )
Note 1
This method compares searchElement to the elements of the array in
descending order using the IsStrictlyEqual algorithm, and if
found at one or more indices, returns the largest such index; otherwise, it returns
-1 𝔽 .
The optional second argument fromIndex defaults to the array's length
minus one (i.e. the whole array is searched). If it is greater than or equal to the
length of the array, the whole array will be searched. If it is less than
-0 𝔽 , it is used as the offset from the end of the
array to compute fromIndex . If the computed index is less than or equal
to +0 𝔽 , -1 𝔽 is
returned.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If len = 0, return -1 𝔽 .
If fromIndex is present, let n be ? ToIntegerOrInfinity (fromIndex );
else let n be len - 1.
If n = -∞, return -1 𝔽 .
If n ≥ 0, then
Let k be min (n , len -
1).
Else,
Let k be len + n .
Repeat, while k ≥ 0,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let elementK be ? Get (O ,
Pk ).
If IsStrictlyEqual (searchElement ,
elementK ) is true , return 𝔽 (k ).
Set k to k - 1.
Return -1 𝔽 .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.21 Array.prototype.map ( callback [ ,
thisArg ] )
Note 1
callback should be a function that accepts three arguments.
map calls callback once for each element in the array, in
ascending order, and constructs a new Array from the results. callback is
called only for elements of the array which actually exist; it is not called for
missing elements of the array.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the element, the
index of the element, and the object being traversed.
map does not directly mutate the object on which it is called but the
object may be mutated by the calls to callback .
The range of elements processed by map is set before the first call to
callback . Elements which are appended to the array after the call to
map begins will not be visited by callback . If existing
elements of the array are changed, their value as passed to callback will
be the value at the time map visits them; elements that are deleted
after the call to map begins and before being visited are not visited.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let A be ? ArraySpeciesCreate (O ,
len ).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Let mappedValue be ? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »).
Perform ? CreateDataPropertyOrThrow (A ,
Pk , mappedValue ).
Set k to k + 1.
Return A .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.22 Array.prototype.pop ( )
Note 1
This method removes the last element of the array and returns it.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If len = 0, then
Perform ? Set (O ,
"length" , +0 𝔽 ,
true ).
Return undefined .
Else,
Assert : len > 0.
Let newLen be 𝔽 (len - 1).
Let index be ! ToString (newLen ).
Let element be ? Get (O ,
index ).
Perform ? DeletePropertyOrThrow (O ,
index ).
Perform ? Set (O ,
"length" , newLen , true ).
Return element .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.23 Array.prototype.push ( ...items )
Note 1
This method appends the arguments to the end of the array, in the order in which they
appear. It returns the new length of the array.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let argCount be the number of elements in items .
If len + argCount > 253 - 1, throw a
TypeError exception.
For each element E of items , do
Perform ? Set (O ,
! ToString (𝔽 (len )),
E , true ).
Set len to len + 1.
Perform ? Set (O ,
"length" , 𝔽 (len ), true ).
Return 𝔽 (len ).
The "length" property of this method is 1 𝔽 .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.24 Array.prototype.reduce ( callback [ ,
initialValue ] )
Note 1
callback should be a function that takes four arguments.
reduce calls the callback, as a function, once for each element after
the first element present in the array, in ascending order.
callback is called with four arguments: the previousValue
(value from the previous call to callback ), the currentValue
(value of the current element), the currentIndex , and the object being
traversed. The first time that callback is called, the previousValue and
currentValue can be one of two values. If an initialValue was
supplied in the call to reduce, then previousValue will be
initialValue and currentValue will be the first value in the
array. If no initialValue was supplied, then previousValue
will be the first value in the array and currentValue will be the second.
It is a TypeError if the array contains no elements and
initialValue is not provided.
reduce does not directly mutate the object on which it is called but the
object may be mutated by the calls to callback .
The range of elements processed by reduce is set before the first call
to callback . Elements that are appended to the array after the call to
reduce begins will not be visited by callback . If existing
elements of the array are changed, their value as passed to callback will
be the value at the time reduce visits them; elements that are deleted
after the call to reduce begins and before being visited are not
visited.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
If len = 0 and initialValue is not present, throw a
TypeError exception.
Let k be 0.
Let accumulator be undefined .
If initialValue is present, then
Set accumulator to initialValue .
Else,
Let kPresent be false .
Repeat, while kPresent is false and
k < len ,
Let Pk be ! ToString (𝔽 (k )).
Set kPresent to ? HasProperty (O ,
Pk ).
If kPresent is true , then
Set accumulator to ? Get (O ,
Pk ).
Set k to k + 1.
If kPresent is false , throw a
TypeError exception.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Set accumulator to ? Call (callback ,
undefined , « accumulator ,
kValue , 𝔽 (k ),
O »).
Set k to k + 1.
Return accumulator .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.25 Array.prototype.reduceRight ( callback [ ,
initialValue ] )
Note 1
callback should be a function that takes four arguments.
reduceRight calls the callback, as a function, once for each element
after the first element present in the array, in descending order.
callback is called with four arguments: the previousValue
(value from the previous call to callback ), the currentValue
(value of the current element), the currentIndex , and the object being
traversed. The first time the function is called, the previousValue and
currentValue can be one of two values. If an initialValue was
supplied in the call to reduceRight, then previousValue will
be initialValue and currentValue will be the last value in the
array. If no initialValue was supplied, then previousValue
will be the last value in the array and currentValue will be the
second-to-last value. It is a TypeError if the array contains no
elements and initialValue is not provided.
reduceRight does not directly mutate the object on which it is called
but the object may be mutated by the calls to callback .
The range of elements processed by reduceRight is set before the first
call to callback . Elements that are appended to the array after the call
to reduceRight begins will not be visited by callback . If
existing elements of the array are changed by callback , their value as
passed to callback will be the value at the time reduceRight
visits them; elements that are deleted after the call to reduceRight
begins and before being visited are not visited.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
If len = 0 and initialValue is not present, throw a
TypeError exception.
Let k be len - 1.
Let accumulator be undefined .
If initialValue is present, then
Set accumulator to initialValue .
Else,
Let kPresent be false .
Repeat, while kPresent is false and
k ≥ 0,
Let Pk be ! ToString (𝔽 (k )).
Set kPresent to ? HasProperty (O ,
Pk ).
If kPresent is true , then
Set accumulator to ? Get (O ,
Pk ).
Set k to k - 1.
If kPresent is false , throw a
TypeError exception.
Repeat, while k ≥ 0,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Set accumulator to ? Call (callback ,
undefined , « accumulator ,
kValue , 𝔽 (k ),
O »).
Set k to k - 1.
Return accumulator .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.26 Array.prototype.reverse ( )
Note 1
This method rearranges the elements of the array so as to reverse their order. It
returns the reversed array.
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let middle be floor (len / 2).
Let lower be 0.
Repeat, while lower ≠ middle ,
Let upper be len - lower - 1.
Let upperP be ! ToString (𝔽 (upper )).
Let lowerP be ! ToString (𝔽 (lower )).
Let lowerExists be ? HasProperty (O ,
lowerP ).
If lowerExists is true , then
Let lowerValue be ? Get (O ,
lowerP ).
Let upperExists be ? HasProperty (O ,
upperP ).
If upperExists is true , then
Let upperValue be ? Get (O ,
upperP ).
If lowerExists is true and
upperExists is true , then
Perform ? Set (O ,
lowerP , upperValue , true ).
Perform ? Set (O ,
upperP , lowerValue , true ).
Else if lowerExists is false and
upperExists is true , then
Perform ? Set (O ,
lowerP , upperValue , true ).
Perform ? DeletePropertyOrThrow (O ,
upperP ).
Else if lowerExists is true and
upperExists is false , then
Perform ? DeletePropertyOrThrow (O ,
lowerP ).
Perform ? Set (O ,
upperP , lowerValue , true ).
Else,
Assert : lowerExists
and upperExists are both false .
NOTE: No action is required.
Set lower to lower + 1.
Return O .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore, it can be transferred to other
kinds of objects for use as a method.
23.1.3.27 Array.prototype.shift ( )
This method removes the first element of the array and returns it.
It performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If len = 0, then
Perform ? Set (O ,
"length" , +0 𝔽 ,
true ).
Return undefined .
Let first be ? Get (O ,
"0" ).
Let k be 1.
Repeat, while k < len ,
Let from be ! ToString (𝔽 (k )).
Let to be ! ToString (𝔽 (k - 1)).
Let fromPresent be ? HasProperty (O ,
from ).
If fromPresent is true , then
Let fromValue be ? Get (O ,
from ).
Perform ? Set (O ,
to , fromValue , true ).
Else,
Assert : fromPresent
is false .
Perform ? DeletePropertyOrThrow (O ,
to ).
Set k to k + 1.
Perform ? DeletePropertyOrThrow (O ,
! ToString (𝔽 (len - 1))).
Perform ? Set (O ,
"length" , 𝔽 (len - 1), true ).
Return first .
Note
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.28 Array.prototype.slice ( start ,
end )
This method returns an array containing the elements of the array from element
start up to, but not including, element end (or through the end of the
array if end is undefined ). If start is negative,
it is treated as length + start
where length is the length of the array. If end is negative, it is
treated as length + end where
length is the length of the array.
It performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let k be 0.
Else if relativeStart < 0, let k be max (len +
relativeStart , 0).
Else, let k be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let final be 0.
Else if relativeEnd < 0, let final be max (len +
relativeEnd , 0).
Else, let final be min (relativeEnd , len ).
Let count be max (final - k , 0).
Let A be ? ArraySpeciesCreate (O ,
count ).
Let n be 0.
Repeat, while k < final ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Perform ? CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (n )),
kValue ).
Set k to k + 1.
Set n to n + 1.
Perform ? Set (A ,
"length" , 𝔽 (n ), true ).
Return A .
Note 1
The explicit setting of the "length" property in step 15 is intended to
ensure the length is correct even when A is not a built-in Array.
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.29 Array.prototype.some ( callback [ ,
thisArg ] )
Note 1
callback should be a function that accepts three arguments and returns a
value that is coercible to a Boolean value. some calls
callback once for each element present in the array, in ascending order,
until it finds one where callback returns true . If
such an element is found, some immediately returns
true . Otherwise, some returns
false . callback is called only for elements of the
array which actually exist; it is not called for missing elements of the array.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the element, the
index of the element, and the object being traversed.
some does not directly mutate the object on which it is called but the
object may be mutated by the calls to callback .
The range of elements processed by some is set before the first call to
callback . Elements that are appended to the array after the call to
some begins will not be visited by callback . If existing
elements of the array are changed, their value as passed to callback will
be the value at the time that some visits them; elements that are
deleted after the call to some begins and before being visited are not
visited. some acts like the "exists" quantifier in mathematics. In
particular, for an empty array, it returns false .
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ? HasProperty (O ,
Pk ).
If kPresent is true , then
Let kValue be ? Get (O ,
Pk ).
Let testResult be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If testResult is true , return
true .
Set k to k + 1.
Return false .
Note 2
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.30 Array.prototype.sort ( comparator )
This method sorts the elements of this array. If comparator is not
undefined , it should be a function that accepts two arguments
x and y and returns a negative Number if x <
y , a positive Number if x > y , or a zero otherwise.
It performs the following steps when called:
If comparator is not
undefined and IsCallable (comparator ) is
false , throw a TypeError exception.
Let obj be ? ToObject (this value).
Let len be ? LengthOfArrayLike (obj ).
Let SortCompare be a new Abstract Closure
with parameters (x , y ) that captures comparator and
performs the following steps when called:
Return ? CompareArrayElements (x ,
y , comparator ).
Let sortedList be ? SortIndexedProperties (obj ,
len , SortCompare , skip-holes ).
Let itemCount be the number of elements in sortedList .
Let j be 0.
Repeat, while j < itemCount ,
Perform ? Set (obj ,
! ToString (𝔽 (j )),
sortedList [j ], true ).
Set j to j + 1.
NOTE: The call to SortIndexedProperties in
step 5 uses
skip-holes . The remaining indices are deleted to preserve the
number of holes that were detected and excluded from the sort.
Repeat, while j < len ,
Perform ? DeletePropertyOrThrow (obj ,
! ToString (𝔽 (j ))).
Set j to j + 1.
Return obj .
Note 1
Because non-existent property values always compare greater than
undefined property values, and undefined
always compares greater than any other value (see CompareArrayElements ),
undefined property values always sort to the end of the result,
followed by non-existent property values.
Note 2
Method calls performed by the ToString abstract
operations in steps 5 and 6 have the potential to
cause SortCompare to not behave as a consistent comparator .
Note 3
This method is intentionally generic; it does not require that its
this value be an Array. Therefore, it can be transferred to other
kinds of objects for use as a method.
23.1.3.30.1 SortIndexedProperties ( obj ,
len , SortCompare , holes )
The abstract operation SortIndexedProperties takes arguments obj (an Object),
len (a non-negative integer ), SortCompare (an Abstract Closure with two
parameters), and holes (skip-holes or
read-through-holes ) and returns either a normal completion
containing a List of ECMAScript language values
or a throw
completion . It performs the following steps when called:
Let items be a new empty List .
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
If holes is skip-holes , then
Let kRead be ? HasProperty (obj ,
Pk ).
Else,
Assert : holes
is read-through-holes .
Let kRead be true .
If kRead is true , then
Let kValue be ? Get (obj ,
Pk ).
Append kValue to items .
Set k to k + 1.
Sort items using an implementation-defined
sequence of calls to SortCompare . If
any such call returns an abrupt
completion , stop before performing any further calls to
SortCompare and return that Completion
Record .
Return items .
The sort order is the ordering of
items after completion of step 4 of the algorithm above.
The sort
order is implementation-defined if
SortCompare is not a consistent
comparator for the elements of items . When
SortIndexedProperties is invoked by Array.prototype.sort or
Array.prototype.toSorted ,
the sort
order is also implementation-defined if
comparator is undefined , and all applications of ToString , to
any specific value passed as an argument to SortCompare , do not produce the
same result.
Unless the sort
order is specified to be implementation-defined , it must
satisfy all of the following conditions:
There must be some mathematical permutation π of the non-negative integers less
than itemCount , such that for every non-negative integer
j less than itemCount , the element old[j ] is exactly the same as new[π(j )] .
Then for all non-negative integers j and k , each
less than itemCount , if ℝ (SortCompare (old[j ],
old[k ])) < 0 , then π(j ) < π(k ) .
And for all non-negative integers j and k such
that j < k < itemCount , if ℝ (SortCompare (old[j ],
old[k ])) = 0 , then π(j )
< π(k ) ; i.e., the sort is stable.
Here the notation old[j ] is used to refer to
items [j ] before step 4 is
executed, and the notation new[j ] to refer
to items [j ] after step 4
has been executed.
An abstract closure or function comparator is a consistent comparator for a set of
values S if all of the requirements below are met for all values
a , b , and c (possibly the same value) in the set
S : The notation a <C
b means ℝ (comparator (a ,
b )) < 0 ; a =C
b means ℝ (comparator (a ,
b )) = 0 ; and a
>C b means ℝ (comparator (a ,
b )) > 0 .
Calling comparator (a , b ) always returns the same
value v when given a specific pair of values a and
b as its two arguments. Furthermore, v is a
Number , and v is not NaN . Note
that this implies that exactly one of a <C b ,
a =C b , and a >C
b will be true for a given pair of a and b .
Calling comparator (a , b ) does not modify
obj or any object on obj 's prototype chain.
a =C a (reflexivity)
If a =C b , then b =C
a (symmetry)
If a =C b and b =C
c , then a =C c (transitivity of
=C )
If a <C b and b <C
c , then a <C c (transitivity of
<C )
If a >C b and b >C
c , then a >C c (transitivity of
>C )
Note
The above conditions are necessary and sufficient to ensure that
comparator divides the set S into equivalence classes and
that these equivalence classes are totally ordered.
23.1.3.30.2 CompareArrayElements ( x ,
y , comparator )
The abstract operation CompareArrayElements takes arguments x (an ECMAScript language value ),
y (an ECMAScript language value ),
and comparator (a function object or
undefined ) and returns either a normal completion
containing a Number or an abrupt
completion . It performs the following steps when called:
If x and y are both undefined , return
+0 𝔽 .
If x is undefined , return
1 𝔽 .
If y is undefined , return
-1 𝔽 .
If comparator is not undefined , then
Let v be ? ToNumber (? Call (comparator ,
undefined , « x , y »)).
If v is NaN , return
+0 𝔽 .
Return v .
Let xString be ? ToString (x ).
Let yString be ? ToString (y ).
Let xSmaller be ! IsLessThan (xString ,
yString , true ).
If xSmaller is true , return
-1 𝔽 .
Let ySmaller be ! IsLessThan (yString ,
xString , true ).
If ySmaller is true , return
1 𝔽 .
Return +0 𝔽 .
23.1.3.31 Array.prototype.splice ( start ,
deleteCount , ...items )
Note 1
This method deletes the deleteCount elements of the array starting at
integer
index start and replaces them with the elements of
items . It returns an Array containing the deleted elements (if any).
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let actualStart be 0.
Else if relativeStart < 0, let actualStart be max (len
+ relativeStart , 0).
Else, let actualStart be min (relativeStart ,
len ).
Let itemCount be the number of elements in items .
If start is not present, then
Let actualDeleteCount be 0.
Else if deleteCount is not present, then
Let actualDeleteCount be len - actualStart .
Else,
Let dc be ? ToIntegerOrInfinity (deleteCount ).
Let actualDeleteCount be the result of clamping
dc between 0 and len - actualStart .
If len + itemCount - actualDeleteCount >
253 - 1, throw a TypeError exception.
Let A be ? ArraySpeciesCreate (O ,
actualDeleteCount ).
Let k be 0.
Repeat, while k < actualDeleteCount ,
Let from be ! ToString (𝔽 (actualStart +
k )).
If ? HasProperty (O ,
from ) is true , then
Let fromValue be ? Get (O ,
from ).
Perform ? CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (k )),
fromValue ).
Set k to k + 1.
Perform ? Set (A ,
"length" , 𝔽 (actualDeleteCount ),
true ).
If itemCount < actualDeleteCount , then
Set k to actualStart .
Repeat, while k < (len -
actualDeleteCount ),
Let from be ! ToString (𝔽 (k +
actualDeleteCount )).
Let to be ! ToString (𝔽 (k +
itemCount )).
If ? HasProperty (O ,
from ) is true , then
Let fromValue be ? Get (O ,
from ).
Perform ? Set (O ,
to , fromValue ,
true ).
Else,
Perform ? DeletePropertyOrThrow (O ,
to ).
Set k to k + 1.
Set k to len .
Repeat, while k > (len -
actualDeleteCount + itemCount ),
Perform ? DeletePropertyOrThrow (O ,
! ToString (𝔽 (k - 1))).
Set k to k - 1.
Else if itemCount > actualDeleteCount , then
Set k to (len - actualDeleteCount ).
Repeat, while k > actualStart ,
Let from be ! ToString (𝔽 (k +
actualDeleteCount - 1)).
Let to be ! ToString (𝔽 (k +
itemCount - 1)).
If ? HasProperty (O ,
from ) is true , then
Let fromValue be ? Get (O ,
from ).
Perform ? Set (O ,
to , fromValue ,
true ).
Else,
Perform ? DeletePropertyOrThrow (O ,
to ).
Set k to k - 1.
Set k to actualStart .
For each element E of items , do
Perform ? Set (O ,
! ToString (𝔽 (k )),
E , true ).
Set k to k + 1.
Perform ? Set (O ,
"length" , 𝔽 (len - actualDeleteCount +
itemCount ), true ).
Return A .
Note 2
The explicit setting of the "length" property in steps 15 and 20 is intended
to ensure the lengths are correct even when the objects are not built-in Arrays.
Note 3
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.32 Array.prototype.toLocaleString ( [
reserved1 [ , reserved2 ] ] )
An ECMAScript implementation that includes the ECMA-402 Internationalization API must
implement this method as specified in the ECMA-402 specification. If an ECMAScript
implementation does not include the ECMA-402 API the following specification of this method
is used.
Note 1
The first edition of ECMA-402 did not include a replacement specification for this
method.
The meanings of the optional parameters to this method are defined in the ECMA-402
specification; implementations that do not include ECMA-402 support must not use those
parameter positions for anything else.
This method performs the following steps when called:
Let array be ? ToObject (this value).
Let len be ? LengthOfArrayLike (array ).
Let separator be the implementation-defined
list-separator String value appropriate for the host environment 's
current locale (such as ", " ).
Let R be the empty String.
Let k be 0.
Repeat, while k < len ,
If k > 0, set R to the string-concatenation of
R and separator .
Let element be ? Get (array ,
! ToString (𝔽 (k ))).
If element is neither undefined nor
null , then
Let S be ? ToString (? Invoke (element ,
"toLocaleString" )).
Set R to the string-concatenation
of R and S .
Set k to k + 1.
Return R .
Note 2
This method converts the elements of the array to Strings using their
toLocaleString methods, and then concatenates these Strings, separated
by occurrences of an implementation-defined
locale-sensitive separator String. This method is analogous to toString
except that it is intended to yield a locale-sensitive result corresponding with
conventions of the host environment 's current locale.
Note 3
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.33 Array.prototype.toReversed ( )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let A be ? ArrayCreate (len ).
Let k be 0.
Repeat, while k < len ,
Let from be ! ToString (𝔽 (len -
k - 1)).
Let Pk be ! ToString (𝔽 (k )).
Let fromValue be ? Get (O ,
from ).
Perform ! CreateDataPropertyOrThrow (A ,
Pk , fromValue ).
Set k to k + 1.
Return A .
23.1.3.34 Array.prototype.toSorted ( comparator )
This method performs the following steps when called:
If comparator is not undefined and IsCallable (comparator ) is
false , throw a TypeError exception.
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let A be ? ArrayCreate (len ).
Let SortCompare be a new Abstract Closure
with parameters (x , y ) that captures comparator and
performs the following steps when called:
Return ? CompareArrayElements (x ,
y , comparator ).
Let sortedList be ? SortIndexedProperties (O ,
len , SortCompare , read-through-holes ).
Let j be 0.
Repeat, while j < len ,
Perform ! CreateDataPropertyOrThrow (A ,
! ToString (𝔽 (j )),
sortedList [j ]).
Set j to j + 1.
Return A .
23.1.3.35 Array.prototype.toSpliced ( start ,
skipCount , ...items )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let actualStart be 0.
Else if relativeStart < 0, let actualStart be max (len
+ relativeStart , 0).
Else, let actualStart be min (relativeStart ,
len ).
Let insertCount be the number of elements in items .
If start is not present, then
Let actualSkipCount be 0.
Else if skipCount is not present, then
Let actualSkipCount be len - actualStart .
Else,
Let sc be ? ToIntegerOrInfinity (skipCount ).
Let actualSkipCount be the result of clamping
sc between 0 and len - actualStart .
Let newLen be len + insertCount -
actualSkipCount .
If newLen > 253 - 1, throw a TypeError
exception.
Let A be ? ArrayCreate (newLen ).
Let i be 0.
Let r be actualStart + actualSkipCount .
Repeat, while i < actualStart ,
Let Pi be ! ToString (𝔽 (i )).
Let iValue be ? Get (O , Pi ).
Perform ! CreateDataPropertyOrThrow (A ,
Pi , iValue ).
Set i to i + 1.
For each element E of items , do
Let Pi be ! ToString (𝔽 (i )).
Perform ! CreateDataPropertyOrThrow (A ,
Pi , E ).
Set i to i + 1.
Repeat, while i < newLen ,
Let Pi be ! ToString (𝔽 (i )).
Let from be ! ToString (𝔽 (r )).
Let fromValue be ? Get (O ,
from ).
Perform ! CreateDataPropertyOrThrow (A ,
Pi , fromValue ).
Set i to i + 1.
Set r to r + 1.
Return A .
23.1.3.36 Array.prototype.toString ( )
This method performs the following steps when called:
Let array be ? ToObject (this value).
Let func be ? Get (array ,
"join" ).
If IsCallable (func ) is
false , set func to the intrinsic function
%Object.prototype.toString%.
Return ? Call (func , array ).
Note
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.37 Array.prototype.unshift ( ...items )
This method prepends the arguments to the start of the array, such that their order within
the array is the same as the order in which they appear in the argument list.
It performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let argCount be the number of elements in items .
If argCount > 0, then
If len + argCount > 253 - 1, throw a
TypeError exception.
Let k be len .
Repeat, while k > 0,
Let from be ! ToString (𝔽 (k - 1)).
Let to be ! ToString (𝔽 (k +
argCount - 1)).
Let fromPresent be ? HasProperty (O ,
from ).
If fromPresent is true , then
Let fromValue be ? Get (O ,
from ).
Perform ? Set (O ,
to , fromValue ,
true ).
Else,
Assert :
fromPresent is false .
Perform ? DeletePropertyOrThrow (O ,
to ).
Set k to k - 1.
Let j be +0 𝔽 .
For each element E of items , do
Perform ? Set (O ,
! ToString (j ),
E , true ).
Set j to j +
1 𝔽 .
Perform ? Set (O ,
"length" , 𝔽 (len + argCount ),
true ).
Return 𝔽 (len + argCount ).
The "length" property of this method is 1 𝔽 .
Note
This method is intentionally generic; it does not require that its
this value be an Array. Therefore it can be transferred to other
kinds of objects for use as a method.
23.1.3.38 Array.prototype.values ( )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Return CreateArrayIterator (O ,
value ).
23.1.3.39 Array.prototype.with ( index ,
value )
This method performs the following steps when called:
Let O be ? ToObject (this value).
Let len be ? LengthOfArrayLike (O ).
Let relativeIndex be ? ToIntegerOrInfinity (index ).
If relativeIndex ≥ 0, let actualIndex be
relativeIndex .
Else, let actualIndex be len + relativeIndex .
If actualIndex ≥ len or actualIndex < 0, throw a
RangeError exception.
Let A be ? ArrayCreate (len ).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
If k = actualIndex , let fromValue be
value .
Else, let fromValue be ? Get (O , Pk ).
Perform ! CreateDataPropertyOrThrow (A ,
Pk , fromValue ).
Set k to k + 1.
Return A .
23.1.3.40 Array.prototype [ %Symbol.iterator% ] ( )
The initial value of the %Symbol.iterator% property is
%Array.prototype.values%, defined in 23.1.3.38 .
23.1.3.41 Array.prototype [ %Symbol.unscopables% ]
The initial value of the %Symbol.unscopables% data
property is an object created by the following steps:
Let unscopableList be OrdinaryObjectCreate (null ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"at" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"copyWithin" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"entries" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"fill" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"find" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"findIndex" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"findLast" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"findLastIndex" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"flat" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"flatMap" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"includes" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"keys" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"toReversed" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"toSorted" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"toSpliced" , true ).
Perform ! CreateDataPropertyOrThrow (unscopableList ,
"values" , true ).
Return unscopableList .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
Note
The own property names of this object are property names that were not included as
standard properties of Array.prototype prior to the ECMAScript 2015
specification. These names are ignored for with statement binding
purposes in order to preserve the behaviour of existing code that might use one of
these names as a binding in an outer scope that is shadowed by a with
statement whose binding object is an Array.
The reason that "with" is not included in the
unscopableList is because it is already a reserved word .
23.1.4 Properties of Array Instances
Array instances are Array exotic objects and have the internal
methods specified for such objects. Array instances inherit properties from the Array prototype
object .
Array instances have a "length" property, and a set of enumerable properties
with array
index names.
23.1.4.1 length
The "length" property of an Array instance is a data
property whose value is always numerically greater than the name of
every configurable own property whose name is an array index .
The "length" property initially has the attributes { [[Writable]] : true , [[Enumerable]] : false , [[Configurable]] : false }.
Note
Reducing the value of the "length" property has the side-effect of
deleting own array elements whose array index is between the old and new
length values. However, non-configurable properties can not be deleted. Attempting
to set the "length" property of an Array to a value that is
numerically less than or equal to the largest numeric own property
name of an existing non-configurable array-indexed property of the array will
result in the length being set to a numeric value that is one greater than that
non-configurable numeric own property name . See 10.4.2.1 .
23.1.5 Array Iterator Objects
An Array Iterator is an object that represents a specific iteration over
some specific Array instance object. There is not a named constructor for Array Iterator
objects. Instead, Array Iterator objects are created by calling certain methods of Array
instance objects.
23.1.5.1 CreateArrayIterator ( array , kind
)
The abstract operation CreateArrayIterator takes arguments array (an Object) and
kind (key+value , key , or
value ) and returns an Object. It is used to create iterator objects for Array methods
that return such iterators . It performs the following
steps when called:
Let iterator be OrdinaryObjectCreate (%ArrayIteratorPrototype% ,
« [[IteratedArrayLike]] , [[ArrayLikeNextIndex]] , [[ArrayLikeIterationKind]] »).
Set iterator .[[IteratedArrayLike]] to
array .
Set iterator .[[ArrayLikeNextIndex]] to 0.
Set iterator .[[ArrayLikeIterationKind]] to
kind .
Return iterator .
23.1.5.2 The %ArrayIteratorPrototype% Object
The %ArrayIteratorPrototype% object:
23.1.5.2.1 %ArrayIteratorPrototype%.next ( )
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
If O does not have all of the internal slots of an Array Iterator
Instance (23.1.5.3 ),
throw a TypeError exception.
Let array be O .[[IteratedArrayLike]] .
If array is undefined , return CreateIteratorResultObject (undefined ,
true ).
Let index be O .[[ArrayLikeNextIndex]] .
Let kind be O .[[ArrayLikeIterationKind]] .
If array has a [[TypedArrayName]] internal
slot, then
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (array ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError
exception.
Let len be TypedArrayLength (taRecord ).
Else,
Let len be ? LengthOfArrayLike (array ).
If index ≥ len , then
Set O .[[IteratedArrayLike]] to
undefined .
Return CreateIteratorResultObject (undefined ,
true ).
Set O .[[ArrayLikeNextIndex]] to
index + 1.
Let indexNumber be 𝔽 (index ).
If kind is key , then
Let result be indexNumber .
Else,
Let elementKey be ! ToString (indexNumber ).
Let elementValue be ? Get (array ,
elementKey ).
If kind is value , then
Let result be elementValue .
Else,
Assert : kind is
key+value .
Let result be CreateArrayFromList («
indexNumber , elementValue »).
Return CreateIteratorResultObject (result ,
false ).
23.1.5.2.2 %ArrayIteratorPrototype% [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is
the String value "Array Iterator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
23.1.5.3 Properties of Array Iterator Instances
Array Iterator instances are
ordinary
objects that inherit properties from the %ArrayIteratorPrototype%
intrinsic object. Array Iterator instances are
initially created with the internal slots listed in Table 74 .
Table 74: Internal Slots of Array
Iterator Instances
Internal Slot
Type
Description
[[IteratedArrayLike]]
an Object or undefined
The array-like object
that is being iterated.
[[ArrayLikeNextIndex]]
a non-negative integer
The integer index of the next
element to be examined by this iterator .
[[ArrayLikeIterationKind]]
key+value , key , or
value
A value that identifies what is returned for each element of the
iteration.
23.2 TypedArray Objects
A TypedArray presents an array-like view of an underlying binary data buffer (25.1 ). A TypedArray element type is the
underlying binary scalar data type that all elements of a TypedArray instance have. There
is a distinct TypedArray constructor , listed in Table 75 , for each of the supported
element types. Each constructor in Table 75 has a corresponding
distinct prototype object.
Table 75: The TypedArray Constructors
Constructor Name and Intrinsic
Element Type
Element Size
Conversion Operation
Description
Int8Array
%Int8Array%
int8
1
ToInt8
8-bit two's complement signed integer
Uint8Array
%Uint8Array%
uint8
1
ToUint8
8-bit unsigned integer
Uint8ClampedArray
%Uint8ClampedArray%
uint8clamped
1
ToUint8Clamp
8-bit unsigned integer (clamped conversion)
Int16Array
%Int16Array%
int16
2
ToInt16
16-bit two's complement signed integer
Uint16Array
%Uint16Array%
uint16
2
ToUint16
16-bit unsigned integer
Int32Array
%Int32Array%
int32
4
ToInt32
32-bit two's complement signed integer
Uint32Array
%Uint32Array%
uint32
4
ToUint32
32-bit unsigned integer
BigInt64Array
%BigInt64Array%
bigint64
8
ToBigInt64
64-bit two's complement signed integer
BigUint64Array
%BigUint64Array%
biguint64
8
ToBigUint64
64-bit unsigned integer
Float16Array
%Float16Array%
float16
2
16-bit IEEE floating point
Float32Array
%Float32Array%
float32
4
32-bit IEEE floating point
Float64Array
%Float64Array%
float64
8
64-bit IEEE floating point
In the definitions below, references to TypedArray should be replaced with the appropriate
constructor name
from the above table.
23.2.1 The %TypedArray% Intrinsic Object
The %TypedArray% intrinsic object:
is a constructor function object that all of
the TypedArray constructor objects inherit from.
along with its corresponding prototype object, provides common properties that are inherited
by all TypedArray constructors and their instances.
does not have a global name or appear as a property of the global
object .
acts as the abstract superclass of the various TypedArray constructors .
will throw an error when invoked, because it is an abstract class constructor .
The TypedArray constructors do not perform a super
call to it.
23.2.1.1 %TypedArray% ( )
This function performs the following steps when called:
Throw a TypeError exception.
The "length" property of this function is
+0 𝔽 .
23.2.2 Properties of the %TypedArray% Intrinsic Object
The %TypedArray% intrinsic object:
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has a "name" property whose value is "TypedArray" .
has the following properties:
23.2.2.1 %TypedArray%.from ( source [ ,
mapper [ , thisArg ] ] )
This method performs the following steps when called:
Let C be the this value.
If IsConstructor (C ) is
false , throw a TypeError exception.
If mapper is undefined , then
Let mapping be false .
Else,
If IsCallable (mapper )
is false , throw a TypeError exception.
Let mapping be true .
Let usingIterator be ? GetMethod (source , %Symbol.iterator% ).
If usingIterator is not undefined , then
Let values be ? IteratorToList (? GetIteratorFromMethod (source ,
usingIterator )).
Let len be the number of elements in values .
Let targetObj be ? TypedArrayCreateFromConstructor (C ,
« 𝔽 (len ) »).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be the first element of values .
Remove the first element from values .
If mapping is true , then
Let mappedValue be ? Call (mapper ,
thisArg , « kValue , 𝔽 (k ) »).
Else,
Let mappedValue be kValue .
Perform ? Set (targetObj ,
Pk , mappedValue , true ).
Set k to k + 1.
Assert : values is now an
empty List .
Return targetObj .
NOTE: source is not an iterable
object , so assume it is already an array-like object .
Let arrayLike be ! ToObject (source ).
Let len be ? LengthOfArrayLike (arrayLike ).
Let targetObj be ? TypedArrayCreateFromConstructor (C ,
« 𝔽 (len ) »).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ? Get (arrayLike ,
Pk ).
If mapping is true , then
Let mappedValue be ? Call (mapper ,
thisArg , « kValue , 𝔽 (k ) »).
Else,
Let mappedValue be kValue .
Perform ? Set (targetObj ,
Pk , mappedValue , true ).
Set k to k + 1.
Return targetObj .
23.2.2.2 %TypedArray%.of ( ...items )
This method performs the following steps when called:
Let len be the number of elements in items .
Let C be the this value.
If IsConstructor (C ) is
false , throw a TypeError exception.
Let newObj be ? TypedArrayCreateFromConstructor (C ,
« 𝔽 (len ) »).
Let k be 0.
Repeat, while k < len ,
Let kValue be items [k ].
Let Pk be ! ToString (𝔽 (k )).
Perform ? Set (newObj ,
Pk , kValue , true ).
Set k to k + 1.
Return newObj .
23.2.2.3 %TypedArray%.prototype
The initial value of %TypedArray% .prototype
is the %TypedArray% prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
23.2.2.4 get %TypedArray% [ %Symbol.species% ]
%TypedArray% [%Symbol.species%]
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
%TypedArray.prototype%
methods normally use their this value's constructor to create a derived object.
However, a subclass constructor may over-ride that default
behaviour by redefining its %Symbol.species% property.
23.2.3 Properties of the %TypedArray% Prototype Object
The %TypedArray% prototype object :
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is %TypedArray.prototype% .
is an ordinary
object .
does not have a [[ViewedArrayBuffer]] or any other of the internal
slots that are specific to TypedArray instance objects.
23.2.3.1 %TypedArray%.prototype.at ( index )
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let relativeIndex be ? ToIntegerOrInfinity (index ).
If relativeIndex ≥ 0, then
Let k be relativeIndex .
Else,
Let k be len + relativeIndex .
If k < 0 or k ≥ len , return
undefined .
Return ! Get (O , ! ToString (𝔽 (k ))).
23.2.3.2 get %TypedArray%.prototype.buffer
%TypedArray% .prototype.buffer
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let buffer be O .[[ViewedArrayBuffer]] .
Return buffer .
23.2.3.3 get %TypedArray%.prototype.byteLength
%TypedArray% .prototype.byteLength
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
Let size be TypedArrayByteLength (taRecord ).
Return 𝔽 (size ).
23.2.3.4 get %TypedArray%.prototype.byteOffset
%TypedArray% .prototype.byteOffset
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , return +0 𝔽 .
Let offset be O .[[ByteOffset]] .
Return 𝔽 (offset ).
23.2.3.5 %TypedArray%.prototype.constructor
The initial value of %TypedArray% .prototype.constructor
is %TypedArray% .
23.2.3.6 %TypedArray%.prototype.copyWithin ( target ,
start [ , end ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.copyWithin as defined in 23.1.3.4 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let relativeTarget be ? ToIntegerOrInfinity (target ).
If relativeTarget = -∞, let targetIndex be 0.
Else if relativeTarget < 0, let targetIndex be max (len
+ relativeTarget , 0).
Else, let targetIndex be min (relativeTarget ,
len ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let startIndex be 0.
Else if relativeStart < 0, let startIndex be max (len
+ relativeStart , 0).
Else, let startIndex be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let endIndex be 0.
Else if relativeEnd < 0, let endIndex be max (len
+ relativeEnd , 0).
Else, let endIndex be min (relativeEnd , len ).
Let count be min (endIndex -
startIndex , len - targetIndex ).
If count > 0, then
NOTE: The copying must be performed in a manner that preserves the bit-level
encoding of the source data.
Let buffer be O .[[ViewedArrayBuffer]] .
Set taRecord to MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Set len to TypedArrayLength (taRecord ).
Let elementSize be TypedArrayElementSize (O ).
Let byteOffset be O .[[ByteOffset]] .
Let bufferByteLimit be (len × elementSize )
+ byteOffset .
Let toByteIndex be (targetIndex ×
elementSize ) + byteOffset .
Let fromByteIndex be (startIndex ×
elementSize ) + byteOffset .
Let countBytes be count × elementSize .
If fromByteIndex < toByteIndex and
toByteIndex < fromByteIndex +
countBytes , then
Let direction be -1.
Set fromByteIndex to fromByteIndex +
countBytes - 1.
Set toByteIndex to toByteIndex +
countBytes - 1.
Else,
Let direction be 1.
Repeat, while countBytes > 0,
If fromByteIndex < bufferByteLimit and
toByteIndex < bufferByteLimit , then
Let value be GetValueFromBuffer (buffer ,
fromByteIndex , uint8 ,
true , unordered ).
Perform SetValueInBuffer (buffer ,
toByteIndex , uint8 ,
value , true ,
unordered ).
Set fromByteIndex to fromByteIndex +
direction .
Set toByteIndex to toByteIndex +
direction .
Set countBytes to countBytes - 1.
Else,
Set countBytes to 0.
Return O .
23.2.3.7 %TypedArray%.prototype.entries ( )
This method performs the following steps when called:
Let O be the this value.
Perform ? ValidateTypedArray (O ,
seq-cst ).
Return CreateArrayIterator (O ,
key+value ).
23.2.3.8 %TypedArray%.prototype.every ( callback [ ,
thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.every as defined in 23.1.3.6 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Let testResult be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If testResult is false , return
false .
Set k to k + 1.
Return true .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.9 %TypedArray%.prototype.fill ( value [ ,
start [ , end ] ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.fill as defined in 23.1.3.7 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If O .[[ContentType]] is
bigint , set value to ? ToBigInt (value ).
Otherwise, set value to ? ToNumber (value ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let startIndex be 0.
Else if relativeStart < 0, let startIndex be max (len
+ relativeStart , 0).
Else, let startIndex be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let endIndex be 0.
Else if relativeEnd < 0, let endIndex be max (len
+ relativeEnd , 0).
Else, let endIndex be min (relativeEnd , len ).
Set taRecord to MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Set len to TypedArrayLength (taRecord ).
Set endIndex to min (endIndex , len ).
Let k be startIndex .
Repeat, while k < endIndex ,
Let Pk be ! ToString (𝔽 (k )).
Perform ! Set (O ,
Pk , value , true ).
Set k to k + 1.
Return O .
23.2.3.10 %TypedArray%.prototype.filter ( callback [
, thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.filter as defined in 23.1.3.8 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let kept be a new empty List .
Let captured be 0.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Let selected be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If selected is true , then
Append kValue to kept .
Set captured to captured + 1.
Set k to k + 1.
Let A be ? TypedArraySpeciesCreate (O , «
𝔽 (captured ) »).
Let n be 0.
For each element e of kept , do
Perform ! Set (A ,
! ToString (𝔽 (n )),
e , true ).
Set n to n + 1.
Return A .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.11 %TypedArray%.prototype.find ( predicate [ ,
thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.find as defined in 23.1.3.9 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let findRec be ? FindViaPredicate (O ,
len , ascending , predicate ,
thisArg ).
Return findRec .[[Value]] .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.12 %TypedArray%.prototype.findIndex (
predicate [ , thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.findIndex as defined in 23.1.3.10 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let findRec be ? FindViaPredicate (O ,
len , ascending , predicate ,
thisArg ).
Return findRec .[[Index]] .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.13 %TypedArray%.prototype.findLast ( predicate
[ , thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.findLast as defined in 23.1.3.11 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let findRec be ? FindViaPredicate (O ,
len , descending , predicate ,
thisArg ).
Return findRec .[[Value]] .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.14 %TypedArray%.prototype.findLastIndex (
predicate [ , thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.findLastIndex as defined in 23.1.3.12 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let findRec be ? FindViaPredicate (O ,
len , descending , predicate ,
thisArg ).
Return findRec .[[Index]] .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.15 %TypedArray%.prototype.forEach ( callback [
, thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.forEach as defined in 23.1.3.15 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Perform ? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »).
Set k to k + 1.
Return undefined .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.16 %TypedArray%.prototype.includes (
searchElement [ , fromIndex ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.includes as defined in 23.1.3.16 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If len = 0, return false .
Let n be ? ToIntegerOrInfinity (fromIndex ).
Assert : If
fromIndex is undefined , then n is 0.
If n = +∞, return false .
Else if n = -∞, set n to 0.
If n ≥ 0, then
Let k be n .
Else,
Let k be len + n .
If k < 0, set k to 0.
Repeat, while k < len ,
Let elementK be ! Get (O ,
! ToString (𝔽 (k ))).
If SameValueZero (searchElement ,
elementK ) is true , return
true .
Set k to k + 1.
Return false .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.17 %TypedArray%.prototype.indexOf (
searchElement [ , fromIndex ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.indexOf as defined in 23.1.3.17 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If len = 0, return -1 𝔽 .
Let n be ? ToIntegerOrInfinity (fromIndex ).
Assert : If
fromIndex is undefined , then n is 0.
If n = +∞, return -1 𝔽 .
Else if n = -∞, set n to 0.
If n ≥ 0, then
Let k be n .
Else,
Let k be len + n .
If k < 0, set k to 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ! HasProperty (O ,
Pk ).
If kPresent is true , then
Let elementK be ! Get (O ,
Pk ).
If IsStrictlyEqual (searchElement ,
elementK ) is true , return 𝔽 (k ).
Set k to k + 1.
Return -1 𝔽 .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.18 %TypedArray%.prototype.join ( separator )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.join as defined in 23.1.3.18 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If separator is undefined , let sep be
"," .
Else, let sep be ? ToString (separator ).
Let R be the empty String.
Let k be 0.
Repeat, while k < len ,
If k > 0, set R to the string-concatenation of
R and sep .
Let element be ! Get (O ,
! ToString (𝔽 (k ))).
If element is not undefined , then
Let S be ! ToString (element ).
Set R to the string-concatenation
of R and S .
Set k to k + 1.
Return R .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.19 %TypedArray%.prototype.keys ( )
This method performs the following steps when called:
Let O be the this value.
Perform ? ValidateTypedArray (O ,
seq-cst ).
Return CreateArrayIterator (O ,
key ).
23.2.3.20 %TypedArray%.prototype.lastIndexOf (
searchElement [ , fromIndex ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.lastIndexOf as defined in 23.1.3.20 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If len = 0, return -1 𝔽 .
If fromIndex is present, let n be ? ToIntegerOrInfinity (fromIndex );
else let n be len - 1.
If n = -∞, return -1 𝔽 .
If n ≥ 0, then
Let k be min (n , len -
1).
Else,
Let k be len + n .
Repeat, while k ≥ 0,
Let Pk be ! ToString (𝔽 (k )).
Let kPresent be ! HasProperty (O ,
Pk ).
If kPresent is true , then
Let elementK be ! Get (O ,
Pk ).
If IsStrictlyEqual (searchElement ,
elementK ) is true , return 𝔽 (k ).
Set k to k - 1.
Return -1 𝔽 .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.21 get %TypedArray%.prototype.length
%TypedArray% .prototype.length
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots.
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , return +0 𝔽 .
Let length be TypedArrayLength (taRecord ).
Return 𝔽 (length ).
This function is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.22 %TypedArray%.prototype.map ( callback [ ,
thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.map as defined in 23.1.3.21 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let A be ? TypedArraySpeciesCreate (O , «
𝔽 (len ) »).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Let mappedValue be ? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »).
Perform ? Set (A , Pk ,
mappedValue , true ).
Set k to k + 1.
Return A .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.23 %TypedArray%.prototype.reduce ( callback [
, initialValue ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.reduce as defined in 23.1.3.24 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
If len = 0 and initialValue is not present, throw a
TypeError exception.
Let k be 0.
Let accumulator be undefined .
If initialValue is present, then
Set accumulator to initialValue .
Else,
Let Pk be ! ToString (𝔽 (k )).
Set accumulator to ! Get (O , Pk ).
Set k to k + 1.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Set accumulator to ? Call (callback ,
undefined , « accumulator , kValue ,
𝔽 (k ), O »).
Set k to k + 1.
Return accumulator .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.24 %TypedArray%.prototype.reduceRight (
callback [ , initialValue ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.reduceRight as defined in 23.1.3.25 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
If len = 0 and initialValue is not present, throw a
TypeError exception.
Let k be len - 1.
Let accumulator be undefined .
If initialValue is present, then
Set accumulator to initialValue .
Else,
Let Pk be ! ToString (𝔽 (k )).
Set accumulator to ! Get (O , Pk ).
Set k to k - 1.
Repeat, while k ≥ 0,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Set accumulator to ? Call (callback ,
undefined , « accumulator , kValue ,
𝔽 (k ), O »).
Set k to k - 1.
Return accumulator .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.25 %TypedArray%.prototype.reverse ( )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.reverse as defined in 23.1.3.26 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let middle be floor (len / 2).
Let lower be 0.
Repeat, while lower ≠ middle ,
Let upper be len - lower - 1.
Let upperP be ! ToString (𝔽 (upper )).
Let lowerP be ! ToString (𝔽 (lower )).
Let lowerValue be ! Get (O ,
lowerP ).
Let upperValue be ! Get (O ,
upperP ).
Perform ! Set (O ,
lowerP , upperValue , true ).
Perform ! Set (O ,
upperP , lowerValue , true ).
Set lower to lower + 1.
Return O .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.26 %TypedArray%.prototype.set ( source [ ,
offset ] )
This method sets multiple values in this TypedArray , reading the values from
source . The details differ based upon the type of source . The optional
offset value indicates the first element index in this TypedArray
where values are written. If omitted, it is assumed to be 0.
It performs the following steps when called:
Let target be the this value.
Perform ? RequireInternalSlot (target ,
[[TypedArrayName]] ).
Assert :
target has a [[ViewedArrayBuffer]] internal
slot.
Let targetOffset be ? ToIntegerOrInfinity (offset ).
If targetOffset < 0, throw a RangeError exception.
If source is an Object that has a [[TypedArrayName]] internal slot, then
Perform ? SetTypedArrayFromTypedArray (target ,
targetOffset , source ).
Else,
Perform ? SetTypedArrayFromArrayLike (target ,
targetOffset , source ).
Return undefined .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.26.1 SetTypedArrayFromArrayLike ( target ,
targetOffset , source )
The abstract operation SetTypedArrayFromArrayLike takes arguments target (a
TypedArray ), targetOffset (a
non-negative integer or +∞), and source (an
ECMAScript language value ,
but not a TypedArray ) and returns either a normal completion
containing unused or a throw
completion . It sets multiple values in target ,
starting at index targetOffset , reading the values from source . It
performs the following steps when called:
Let targetRecord be MakeTypedArrayWithBufferWitnessRecord (target ,
seq-cst ).
If IsTypedArrayOutOfBounds (targetRecord )
is true , throw a TypeError exception.
Let targetLength be TypedArrayLength (targetRecord ).
Let src be ? ToObject (source ).
Let srcLength be ? LengthOfArrayLike (src ).
If targetOffset = +∞, throw a RangeError
exception.
If srcLength + targetOffset > targetLength ,
throw a RangeError exception.
Let k be 0.
Repeat, while k < srcLength ,
Let Pk be ! ToString (𝔽 (k )).
Let value be ? Get (src ,
Pk ).
Let targetIndex be 𝔽 (targetOffset +
k ).
Perform ? TypedArraySetElement (target ,
targetIndex , value ).
Set k to k + 1.
Return unused .
23.2.3.26.2 SetTypedArrayFromTypedArray ( target ,
targetOffset , source )
The abstract operation SetTypedArrayFromTypedArray takes arguments target (a
TypedArray ), targetOffset (a
non-negative integer or +∞), and source (a
TypedArray ) and returns either a normal completion
containing unused or a throw
completion . It sets multiple values in target ,
starting at index targetOffset , reading the values from source . It
performs the following steps when called:
Let targetBuffer be target .[[ViewedArrayBuffer]] .
Let targetRecord be MakeTypedArrayWithBufferWitnessRecord (target ,
seq-cst ).
If IsTypedArrayOutOfBounds (targetRecord )
is true , throw a TypeError exception.
Let targetLength be TypedArrayLength (targetRecord ).
Let srcBuffer be source .[[ViewedArrayBuffer]] .
Let srcRecord be MakeTypedArrayWithBufferWitnessRecord (source ,
seq-cst ).
If IsTypedArrayOutOfBounds (srcRecord )
is true , throw a TypeError exception.
Let srcLength be TypedArrayLength (srcRecord ).
Let targetType be TypedArrayElementType (target ).
Let targetElementSize be TypedArrayElementSize (target ).
Let targetByteOffset be target .[[ByteOffset]] .
Let srcType be TypedArrayElementType (source ).
Let srcElementSize be TypedArrayElementSize (source ).
Let srcByteOffset be source .[[ByteOffset]] .
If targetOffset = +∞, throw a RangeError
exception.
If srcLength + targetOffset > targetLength ,
throw a RangeError exception.
If target .[[ContentType]] is not
source .[[ContentType]] , throw a
TypeError exception.
If IsSharedArrayBuffer (srcBuffer )
is true , IsSharedArrayBuffer (targetBuffer )
is true , and srcBuffer .[[ArrayBufferData]] is targetBuffer .[[ArrayBufferData]] , let
sameSharedArrayBuffer be true ; otherwise let
sameSharedArrayBuffer be false .
If SameValue (srcBuffer ,
targetBuffer ) is true or
sameSharedArrayBuffer is true , then
Let srcByteLength be TypedArrayByteLength (srcRecord ).
Set srcBuffer to ? CloneArrayBuffer (srcBuffer ,
srcByteOffset , srcByteLength ).
Let srcByteIndex be 0.
Else,
Let srcByteIndex be srcByteOffset .
Let targetByteIndex be (targetOffset ×
targetElementSize ) + targetByteOffset .
Let limit be targetByteIndex +
(targetElementSize × srcLength ).
If srcType is targetType , then
NOTE: The transfer must be performed in a manner that preserves the
bit-level encoding of the source data.
Repeat, while targetByteIndex < limit ,
Let value be GetValueFromBuffer (srcBuffer ,
srcByteIndex , uint8 ,
true , unordered ).
Perform SetValueInBuffer (targetBuffer ,
targetByteIndex , uint8 ,
value , true ,
unordered ).
Set srcByteIndex to srcByteIndex + 1.
Set targetByteIndex to targetByteIndex +
1.
Else,
Repeat, while targetByteIndex < limit ,
Let value be GetValueFromBuffer (srcBuffer ,
srcByteIndex , srcType ,
true , unordered ).
Perform SetValueInBuffer (targetBuffer ,
targetByteIndex , targetType ,
value , true ,
unordered ).
Set srcByteIndex to srcByteIndex +
srcElementSize .
Set targetByteIndex to targetByteIndex +
targetElementSize .
Return unused .
23.2.3.27 %TypedArray%.prototype.slice ( start ,
end )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.slice as defined in 23.1.3.28 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let srcArrayLength be TypedArrayLength (taRecord ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let startIndex be 0.
Else if relativeStart < 0, let startIndex be max (srcArrayLength +
relativeStart , 0).
Else, let startIndex be min (relativeStart ,
srcArrayLength ).
If end is undefined , let relativeEnd be
srcArrayLength ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let endIndex be 0.
Else if relativeEnd < 0, let endIndex be max (srcArrayLength +
relativeEnd , 0).
Else, let endIndex be min (relativeEnd ,
srcArrayLength ).
Let countBytes be max (endIndex -
startIndex , 0).
Let A be ? TypedArraySpeciesCreate (O , «
𝔽 (countBytes ) »).
If countBytes > 0, then
Set taRecord to MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Set endIndex to min (endIndex , TypedArrayLength (taRecord )).
Set countBytes to max (endIndex -
startIndex , 0).
Let srcType be TypedArrayElementType (O ).
Let targetType be TypedArrayElementType (A ).
If srcType is targetType , then
NOTE: The transfer must be performed in a manner that preserves the
bit-level encoding of the source data.
Let srcBuffer be O .[[ViewedArrayBuffer]] .
Let targetBuffer be A .[[ViewedArrayBuffer]] .
Let elementSize be TypedArrayElementSize (O ).
Let srcByteOffset be O .[[ByteOffset]] .
Let srcByteIndex be (startIndex ×
elementSize ) + srcByteOffset .
Let targetByteIndex be A .[[ByteOffset]] .
Let endByteIndex be targetByteIndex +
(countBytes × elementSize ).
Repeat, while targetByteIndex <
endByteIndex ,
Let value be GetValueFromBuffer (srcBuffer ,
srcByteIndex , uint8 ,
true , unordered ).
Perform SetValueInBuffer (targetBuffer ,
targetByteIndex , uint8 ,
value , true ,
unordered ).
Set srcByteIndex to srcByteIndex + 1.
Set targetByteIndex to targetByteIndex
+ 1.
Else,
Let n be 0.
Let k be startIndex .
Repeat, while k < endIndex ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O ,
Pk ).
Perform ! Set (A ,
! ToString (𝔽 (n )),
kValue , true ).
Set k to k + 1.
Set n to n + 1.
Return A .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.28 %TypedArray%.prototype.some ( callback [ ,
thisArg ] )
The interpretation and use of the arguments of this method are the same as for
Array.prototype.some as defined in 23.1.3.29 .
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ! Get (O , Pk ).
Let testResult be ToBoolean (? Call (callback ,
thisArg , « kValue , 𝔽 (k ),
O »)).
If testResult is true , return
true .
Set k to k + 1.
Return false .
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.29 %TypedArray%.prototype.sort ( comparator )
This is a distinct method that, except as described below, implements the same requirements
as those of Array.prototype.sort as defined in 23.1.3.30 . The implementation of
this method may be optimized with the knowledge that the this value is an
object that has a fixed length and whose integer-indexed properties are not sparse.
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
It performs the following steps when called:
If comparator is not undefined and IsCallable (comparator ) is
false , throw a TypeError exception.
Let obj be the this value.
Let taRecord be ? ValidateTypedArray (obj ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
NOTE: The following closure performs a numeric comparison rather than the string
comparison used in 23.1.3.30 .
Let SortCompare be a new Abstract Closure
with parameters (x , y ) that captures comparator and
performs the following steps when called:
Return ? CompareTypedArrayElements (x ,
y , comparator ).
Let sortedList be ? SortIndexedProperties (obj ,
len , SortCompare , read-through-holes ).
Let j be 0.
Repeat, while j < len ,
Perform ! Set (obj ,
! ToString (𝔽 (j )),
sortedList [j ], true ).
Set j to j + 1.
Return obj .
Note
Because NaN always compares greater than any other value (see
CompareTypedArrayElements ),
NaN property values always sort to the end of the result when
comparator is not provided.
23.2.3.30 %TypedArray%.prototype.subarray ( start ,
end )
This method returns a new TypedArray whose element type is the element type of
this TypedArray and whose ArrayBuffer is the ArrayBuffer of this
TypedArray , referencing the elements in the interval from start
(inclusive) to end (exclusive). If either start or end is
negative, it refers to an index from the end of the array, as opposed to from the beginning.
It performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let buffer be O .[[ViewedArrayBuffer]] .
Let srcRecord be MakeTypedArrayWithBufferWitnessRecord (O ,
seq-cst ).
If IsTypedArrayOutOfBounds (srcRecord )
is true , then
Let srcLength be 0.
Else,
Let srcLength be TypedArrayLength (srcRecord ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let startIndex be 0.
Else if relativeStart < 0, let startIndex be max (srcLength +
relativeStart , 0).
Else, let startIndex be min (relativeStart ,
srcLength ).
Let elementSize be TypedArrayElementSize (O ).
Let srcByteOffset be O .[[ByteOffset]] .
Let beginByteOffset be srcByteOffset + (startIndex
× elementSize ).
If O .[[ArrayLength]] is
auto and end is undefined , then
Let argumentsList be « buffer , 𝔽 (beginByteOffset ) ».
Else,
If end is undefined , let
relativeEnd be srcLength ; else let
relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let endIndex be 0.
Else if relativeEnd < 0, let endIndex be max (srcLength +
relativeEnd , 0).
Else, let endIndex be min (relativeEnd ,
srcLength ).
Let newLength be max (endIndex -
startIndex , 0).
Let argumentsList be « buffer , 𝔽 (beginByteOffset ), 𝔽 (newLength ) ».
Return ? TypedArraySpeciesCreate (O ,
argumentsList ).
This method is not generic. The this value must be an object with a [[TypedArrayName]] internal slot.
23.2.3.31 %TypedArray%.prototype.toLocaleString ( [
reserved1 [ , reserved2 ] ] )
This is a distinct method that implements the same algorithm as
Array.prototype.toLocaleString as defined in 23.1.3.32 except that
TypedArrayLength is called in place of
performing a [[Get]] of "length" . The
implementation of the algorithm may be optimized with the knowledge that the
this value has a fixed length when the underlying buffer is not resizable
and whose integer-indexed properties are not sparse.
However, such optimization must not introduce any observable changes in the specified
behaviour of the algorithm.
This method is not generic. ValidateTypedArray is called with the
this value and seq-cst as arguments prior to
evaluating the algorithm. If its result is an abrupt completion
that exception is thrown instead of evaluating the algorithm.
Note
If the ECMAScript implementation includes the ECMA-402 Internationalization API this
method is based upon the algorithm for Array.prototype.toLocaleString
that is in the ECMA-402 specification.
23.2.3.32 %TypedArray%.prototype.toReversed ( )
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let length be TypedArrayLength (taRecord ).
Let A be ? TypedArrayCreateSameType (O , «
𝔽 (length ) »).
Let k be 0.
Repeat, while k < length ,
Let from be ! ToString (𝔽 (length -
k - 1)).
Let Pk be ! ToString (𝔽 (k )).
Let fromValue be ! Get (O ,
from ).
Perform ! Set (A ,
Pk , fromValue , true ).
Set k to k + 1.
Return A .
23.2.3.33 %TypedArray%.prototype.toSorted (
comparator )
This method performs the following steps when called:
If comparator is not undefined and IsCallable (comparator ) is
false , throw a TypeError exception.
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let A be ? TypedArrayCreateSameType (O , «
𝔽 (len ) »).
NOTE: The following closure performs a numeric comparison rather than the string
comparison used in 23.1.3.34 .
Let SortCompare be a new Abstract Closure
with parameters (x , y ) that captures comparator and
performs the following steps when called:
Return ? CompareTypedArrayElements (x ,
y , comparator ).
Let sortedList be ? SortIndexedProperties (O ,
len , SortCompare , read-through-holes ).
Let j be 0.
Repeat, while j < len ,
Perform ! Set (A ,
! ToString (𝔽 (j )),
sortedList [j ], true ).
Set j to j + 1.
Return A .
23.2.3.34 %TypedArray%.prototype.toString ( )
The initial value of the "toString" property is
%Array.prototype.toString%, defined in 23.1.3.36 .
23.2.3.35 %TypedArray%.prototype.values ( )
This method performs the following steps when called:
Let O be the this value.
Perform ? ValidateTypedArray (O ,
seq-cst ).
Return CreateArrayIterator (O ,
value ).
23.2.3.36 %TypedArray%.prototype.with ( index ,
value )
This method performs the following steps when called:
Let O be the this value.
Let taRecord be ? ValidateTypedArray (O ,
seq-cst ).
Let len be TypedArrayLength (taRecord ).
Let relativeIndex be ? ToIntegerOrInfinity (index ).
If relativeIndex ≥ 0, let actualIndex be
relativeIndex .
Else, let actualIndex be len + relativeIndex .
If O .[[ContentType]] is
bigint , let numericValue be ? ToBigInt (value ).
Else, let numericValue be ? ToNumber (value ).
If IsValidIntegerIndex (O ,
𝔽 (actualIndex )) is
false , throw a RangeError exception.
Let A be ? TypedArrayCreateSameType (O , «
𝔽 (len ) »).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
If k = actualIndex , let fromValue be
numericValue .
Else, let fromValue be ! Get (O ,
Pk ).
Perform ! Set (A ,
Pk , fromValue , true ).
Set k to k + 1.
Return A .
23.2.3.37 %TypedArray%.prototype [ %Symbol.iterator% ] ( )
The initial value of the %Symbol.iterator% property is
%TypedArray.prototype.values%, defined in 23.2.3.35 .
23.2.3.38 get %TypedArray%.prototype [ %Symbol.toStringTag% ]
%TypedArray% .prototype[%Symbol.toStringTag%]
is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
If O is not an Object , return
undefined .
If O does not have a [[TypedArrayName]] internal
slot, return undefined .
Let name be O .[[TypedArrayName]] .
Assert :
name is a
String .
Return name .
This property has the attributes { [[Enumerable]] :
false , [[Configurable]] : true
}.
The initial value of the "name" property of this function is "get
[Symbol.toStringTag]" .
23.2.4 Abstract Operations for TypedArray Objects
23.2.4.1 TypedArrayCreateFromConstructor (
constructor , argumentList )
The abstract operation TypedArrayCreateFromConstructor takes arguments constructor
(a constructor ) and argumentList (a
List of ECMAScript language values ) and
returns either a normal completion
containing a TypedArray or a throw completion . It
is used to specify the creation of a new TypedArray using a constructor function. It performs
the following steps when called:
Let newTypedArray be ? Construct (constructor ,
argumentList ).
Let taRecord be ? ValidateTypedArray (newTypedArray ,
seq-cst ).
Assert :
newTypedArray has all the internal slots mentioned in Properties of
TypedArray Instances .
If the number of elements in argumentList is 1 and
argumentList [0] is a
Number , then
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Let length be TypedArrayLength (taRecord ).
If length < ℝ (argumentList [0]), throw a
TypeError exception.
Return newTypedArray .
23.2.4.2 TypedArrayCreateSameType ( exemplar ,
argumentList )
The abstract operation TypedArrayCreateSameType takes arguments exemplar (a
TypedArray ) and argumentList (a
List of ECMAScript language values ) and
returns either a normal completion
containing a TypedArray or a throw completion . It
is used to specify the creation of a new TypedArray using a constructor function that is
derived from exemplar . Unlike TypedArraySpeciesCreate , which can
construct custom TypedArray subclasses through the use of %Symbol.species% , this operation
always uses one of the built-in TypedArray constructors . It performs the
following steps when called:
Let constructor be the intrinsic object associated with the constructor name exemplar .[[TypedArrayName]] in Table 75 .
Let result be ? TypedArrayCreateFromConstructor (constructor ,
argumentList ).
Assert :
result .[[ContentType]] is
exemplar .[[ContentType]] .
Return result .
23.2.4.3 TypedArraySpeciesCreate ( exemplar ,
argumentList )
The abstract operation TypedArraySpeciesCreate takes arguments exemplar (a
TypedArray ) and argumentList (a
List of ECMAScript language values ) and
returns either a normal completion
containing a TypedArray or a throw completion . It
is used to specify the creation of a new TypedArray using a constructor function that is
derived from exemplar . Unlike ArraySpeciesCreate ,
which can create non-Array objects through the use of %Symbol.species% , this operation
enforces that the constructor function creates an actual TypedArray . It
performs the following steps when called:
Let defaultConstructor be the intrinsic object associated with the
constructor name exemplar .[[TypedArrayName]] in Table 75 .
Let constructor be ? SpeciesConstructor (exemplar ,
defaultConstructor ).
Let result be ? TypedArrayCreateFromConstructor (constructor ,
argumentList ).
If result .[[ContentType]] is not
exemplar .[[ContentType]] , throw a
TypeError exception.
Return result .
23.2.4.4 ValidateTypedArray ( O , order )
The abstract operation ValidateTypedArray takes arguments O (an ECMAScript language value ) and
order (seq-cst or unordered ) and
returns either a normal completion
containing a TypedArray With Buffer Witness
Record or a throw completion . It
performs the following steps when called:
Perform ? RequireInternalSlot (O ,
[[TypedArrayName]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (O ,
order ).
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Return taRecord .
23.2.4.5 TypedArrayElementSize ( O )
The abstract operation TypedArrayElementSize takes argument O (a TypedArray ) and
returns a non-negative integer . It performs the following steps when called:
Return the Element Size value specified in Table 75 for
O .[[TypedArrayName]] .
23.2.4.6 TypedArrayElementType ( O )
The abstract operation TypedArrayElementType takes argument O (a TypedArray ) and
returns a TypedArray element type . It performs
the following steps when called:
Return the Element Type value specified in Table 75 for
O .[[TypedArrayName]] .
23.2.4.7 CompareTypedArrayElements ( x , y ,
comparator )
The abstract operation CompareTypedArrayElements takes arguments x (a Number or a
BigInt), y (a Number or a BigInt), and comparator (a function
object or undefined ) and returns either a
normal completion
containing a Number or an abrupt completion .
It performs the following steps when called:
Assert :
x is a
Number and y is a
Number , or x is a BigInt
and y is a
BigInt .
If comparator is not undefined , then
Let v be ? ToNumber (?
Call (comparator ,
undefined , « x , y »)).
If v is NaN , return
+0 𝔽 .
Return v .
If x and y are both NaN , return
+0 𝔽 .
If x is NaN , return 1 𝔽 .
If y is NaN , return
-1 𝔽 .
If x < y , return -1 𝔽 .
If x > y , return 1 𝔽 .
If x is -0 𝔽 and y is
+0 𝔽 , return -1 𝔽 .
If x is +0 𝔽 and y is
-0 𝔽 , return 1 𝔽 .
Return +0 𝔽 .
Note
This performs a numeric comparison rather than the string comparison used in
23.1.3.30.2 .
23.2.5 The TypedArray Constructors
Each TypedArray constructor :
is an intrinsic object that has the structure described below, differing only in the name
used as the constructor name instead of
TypedArray , in Table 75 .
is a function whose behaviour differs based upon the number and types of its arguments. The
actual behaviour of a call of TypedArray depends upon the number and kind of
arguments that are passed to it.
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
TypedArray behaviour must include a super call to the
TypedArray constructor to create and initialize the subclass
instance with the internal state necessary to support the %TypedArray% .prototype
built-in methods.
23.2.5.1 TypedArray ( ...args )
Each TypedArray constructor performs the following steps when
called:
If NewTarget is undefined , throw a TypeError
exception.
Let constructorName be the String value of the Constructor Name value specified in
Table 75 for this
TypedArray constructor .
Let proto be "%TypedArray .prototype%".
Let numberOfArgs be the number of elements in args .
If numberOfArgs = 0, then
Return ? AllocateTypedArray (constructorName ,
NewTarget, proto , 0).
Else,
Let firstArgument be args [0].
If firstArgument is an Object ,
then
Let O be ? AllocateTypedArray (constructorName ,
NewTarget, proto ).
If firstArgument has a [[TypedArrayName]] internal slot, then
Perform ? InitializeTypedArrayFromTypedArray (O ,
firstArgument ).
Else if firstArgument has an [[ArrayBufferData]] internal slot, then
If numberOfArgs > 1, let byteOffset
be args [1]; else let byteOffset be
undefined .
If numberOfArgs > 2, let length be
args [2]; else let length be
undefined .
Perform ? InitializeTypedArrayFromArrayBuffer (O ,
firstArgument , byteOffset ,
length ).
Else,
Assert :
firstArgument is an
Object and firstArgument
does not have either a [[TypedArrayName]] or an [[ArrayBufferData]] internal slot.
Let usingIterator be ? GetMethod (firstArgument ,
%Symbol.iterator% ).
If usingIterator is not
undefined , then
Let values be ? IteratorToList (?
GetIteratorFromMethod (firstArgument ,
usingIterator )).
Perform ? InitializeTypedArrayFromList (O ,
values ).
Else,
NOTE: firstArgument is not an iterable
object , so assume it is
already an array-like
object .
Perform ? InitializeTypedArrayFromArrayLike (O ,
firstArgument ).
Return O .
Else,
Assert :
firstArgument is not an
Object .
Let elementLength be ? ToIndex (firstArgument ).
Return ? AllocateTypedArray (constructorName ,
NewTarget, proto , elementLength ).
23.2.5.1.1 AllocateTypedArray ( constructorName ,
newTarget , defaultProto [ , length ] )
The abstract operation AllocateTypedArray takes arguments constructorName (a
String which is the name of a TypedArray constructor in Table 75 ),
newTarget (a constructor ), and defaultProto (a
String) and optional argument length (a non-negative integer ) and
returns either a normal
completion containing a TypedArray or a throw
completion . It is used to validate and create an instance of a
TypedArray constructor . If the
length argument is passed, an ArrayBuffer of that length is also allocated
and associated with the new TypedArray instance. AllocateTypedArray
provides common semantics that is used by TypedArray . It performs the
following steps when called:
Let proto be ? GetPrototypeFromConstructor (newTarget ,
defaultProto ).
Let obj be TypedArrayCreate (proto ).
Assert : obj .[[ViewedArrayBuffer]] is undefined .
Set obj .[[TypedArrayName]] to
constructorName .
If constructorName is either "BigInt64Array" or
"BigUint64Array" , set obj .[[ContentType]] to bigint .
Otherwise, set obj .[[ContentType]] to
number .
If length is not present, then
Set obj .[[ByteLength]] to 0.
Set obj .[[ByteOffset]] to 0.
Set obj .[[ArrayLength]] to 0.
Else,
Perform ? AllocateTypedArrayBuffer (obj ,
length ).
Return obj .
23.2.5.1.2 InitializeTypedArrayFromTypedArray (
O , srcArray )
The abstract operation InitializeTypedArrayFromTypedArray takes arguments O (a
TypedArray ) and srcArray (a
TypedArray ) and returns either a normal completion
containing unused or a throw
completion . It performs the following steps when called:
Let srcData be srcArray .[[ViewedArrayBuffer]] .
Let elementType be TypedArrayElementType (O ).
Let elementSize be TypedArrayElementSize (O ).
Let srcType be TypedArrayElementType (srcArray ).
Let srcElementSize be TypedArrayElementSize (srcArray ).
Let srcByteOffset be srcArray .[[ByteOffset]] .
Let srcRecord be MakeTypedArrayWithBufferWitnessRecord (srcArray ,
seq-cst ).
If IsTypedArrayOutOfBounds (srcRecord )
is true , throw a TypeError exception.
Let elementLength be TypedArrayLength (srcRecord ).
Let byteLength be elementSize × elementLength .
If elementType is srcType , then
Let data be ? CloneArrayBuffer (srcData ,
srcByteOffset , byteLength ).
Else,
Let data be ? AllocateArrayBuffer (%ArrayBuffer% ,
byteLength ).
If srcArray .[[ContentType]] is not
O .[[ContentType]] , throw a
TypeError exception.
Let srcByteIndex be srcByteOffset .
Let targetByteIndex be 0.
Let count be elementLength .
Repeat, while count > 0,
Let value be GetValueFromBuffer (srcData ,
srcByteIndex , srcType ,
true , unordered ).
Perform SetValueInBuffer (data ,
targetByteIndex , elementType ,
value , true ,
unordered ).
Set srcByteIndex to srcByteIndex +
srcElementSize .
Set targetByteIndex to targetByteIndex +
elementSize .
Set count to count - 1.
Set O .[[ViewedArrayBuffer]] to
data .
Set O .[[ByteLength]] to
byteLength .
Set O .[[ByteOffset]] to 0.
Set O .[[ArrayLength]] to
elementLength .
Return unused .
23.2.5.1.3 InitializeTypedArrayFromArrayBuffer (
O , buffer , byteOffset , length )
The abstract operation InitializeTypedArrayFromArrayBuffer takes arguments O
(a TypedArray ), buffer (an ArrayBuffer
or a SharedArrayBuffer), byteOffset (an ECMAScript language value ),
and length (an ECMAScript language
value ) and returns either a normal completion
containing unused or a throw
completion . It performs the following steps when called:
Let elementSize be TypedArrayElementSize (O ).
Let offset be ? ToIndex (byteOffset ).
If offset modulo elementSize ≠ 0,
throw a RangeError exception.
Let bufferIsFixedLength be IsFixedLengthArrayBuffer (buffer ).
If length is not undefined , then
Let newLength be ? ToIndex (length ).
If IsDetachedBuffer (buffer )
is true , throw a TypeError exception.
Let bufferByteLength be ArrayBufferByteLength (buffer ,
seq-cst ).
If length is undefined and
bufferIsFixedLength is false , then
If offset > bufferByteLength , throw a
RangeError exception.
Set O .[[ByteLength]] to
auto .
Set O .[[ArrayLength]] to
auto .
Else,
If length is undefined , then
If bufferByteLength modulo
elementSize ≠ 0, throw a
RangeError exception.
Let newByteLength be bufferByteLength -
offset .
If newByteLength < 0, throw a
RangeError exception.
Else,
Let newByteLength be newLength ×
elementSize .
If offset + newByteLength >
bufferByteLength , throw a
RangeError exception.
Set O .[[ByteLength]] to
newByteLength .
Set O .[[ArrayLength]] to
newByteLength / elementSize .
Set O .[[ViewedArrayBuffer]] to
buffer .
Set O .[[ByteOffset]] to offset .
Return unused .
23.2.5.1.4 InitializeTypedArrayFromList ( O ,
values )
The abstract operation InitializeTypedArrayFromList takes arguments O (a
TypedArray ) and values (a List of ECMAScript language values )
and returns either a normal
completion containing unused or a
throw
completion . It performs the following steps when called:
Let len be the number of elements in values .
Perform ? AllocateTypedArrayBuffer (O ,
len ).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be the first element of values .
Remove the first element from values .
Perform ? Set (O ,
Pk , kValue , true ).
Set k to k + 1.
Assert : values is now an empty
List .
Return unused .
23.2.5.1.5 InitializeTypedArrayFromArrayLike ( O ,
arrayLike )
The abstract operation InitializeTypedArrayFromArrayLike takes arguments O (a
TypedArray ) and arrayLike (an
Object, but not a TypedArray or an ArrayBuffer) and returns
either a normal completion
containing unused or a throw
completion . It performs the following steps when called:
Let len be ? LengthOfArrayLike (arrayLike ).
Perform ? AllocateTypedArrayBuffer (O ,
len ).
Let k be 0.
Repeat, while k < len ,
Let Pk be ! ToString (𝔽 (k )).
Let kValue be ? Get (arrayLike ,
Pk ).
Perform ? Set (O ,
Pk , kValue , true ).
Set k to k + 1.
Return unused .
23.2.5.1.6 AllocateTypedArrayBuffer ( O ,
length )
The abstract operation AllocateTypedArrayBuffer takes arguments O (a TypedArray )
and length (a non-negative integer ) and returns either a normal completion
containing unused or a throw
completion . It allocates and associates an ArrayBuffer with
O . It performs the following steps when called:
Assert : O .[[ViewedArrayBuffer]] is undefined .
Let elementSize be TypedArrayElementSize (O ).
Let byteLength be elementSize × length .
Let data be ? AllocateArrayBuffer (%ArrayBuffer% ,
byteLength ).
Set O .[[ViewedArrayBuffer]] to
data .
Set O .[[ByteLength]] to
byteLength .
Set O .[[ByteOffset]] to 0.
Set O .[[ArrayLength]] to length .
Return unused .
23.2.6 Properties of the TypedArray Constructors
Each TypedArray constructor :
has a [[Prototype]] internal slot whose value is %TypedArray% .
has a "length" property whose value is 3 𝔽 .
has a "name" property whose value is the String value of the constructor
name specified for it in Table 75 .
has the following properties:
23.2.6.1 TypedArray .BYTES_PER_ELEMENT
The value of TypedArray .BYTES_PER_ELEMENT is the Element Size value
specified in Table 75 for
TypedArray .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
23.2.6.2 TypedArray .prototype
The initial value of TypedArray .prototype is the corresponding
TypedArray prototype intrinsic object (23.2.7 ).
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
23.2.7 Properties of the TypedArray Prototype Objects
Each TypedArray prototype object:
has a [[Prototype]] internal slot whose value is %TypedArray.prototype% .
is an ordinary
object .
does not have a [[ViewedArrayBuffer]] or any other of the internal
slots that are specific to TypedArray instance objects.
23.2.7.1 TypedArray .prototype.BYTES_PER_ELEMENT
The value of TypedArray .prototype.BYTES_PER_ELEMENT is the Element
Size value specified in Table 75 for
TypedArray .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
23.2.7.2 TypedArray .prototype.constructor
The initial value of the "constructor" property of the prototype for a
given TypedArray constructor is the constructor itself.
23.2.8 Properties of TypedArray Instances
TypedArray instances are TypedArrays . Each TypedArray instance
inherits properties from the corresponding TypedArray prototype object. Each
TypedArray instance has the following internal slots: [[ViewedArrayBuffer]] , [[TypedArrayName]] , [[ContentType]] , [[ByteLength]] , [[ByteOffset]] , and [[ArrayLength]] .
24 Keyed Collections
24.1 Map Objects
Maps are collections of key/value pairs where both the keys and values may be arbitrary ECMAScript language values . A distinct
key value may only occur in one key/value pair within the Map's collection. Distinct key values are
discriminated using the semantics of the SameValueZero comparison algorithm.
Maps must be implemented using either hash tables or other mechanisms that, on average, provide
access times that are sublinear on the number of elements in the collection. The data structure used
in this specification is only intended to describe the required observable semantics of Maps. It is
not intended to be a viable implementation model.
24.1.1 The Map Constructor
The Map constructor :
is %Map% .
is the initial value of the "Map" property of the global
object .
creates and initializes a new Map when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Map behaviour must include a super call to the Map constructor to
create and initialize the subclass instance with the internal state necessary to support the
Map.prototype built-in methods.
24.1.1.1 Map ( [ iterable ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let map be ? OrdinaryCreateFromConstructor (NewTarget,
"%Map.prototype%" , « [[MapData]] »).
Set map .[[MapData]] to a new empty List .
If iterable is either undefined or
null , return map .
Let adder be ? Get (map ,
"set" ).
If IsCallable (adder ) is
false , throw a TypeError exception.
Return ? AddEntriesFromIterable (map ,
iterable , adder ).
Note
If the parameter iterable is present, it is expected to be an object that
implements a %Symbol.iterator% method that
returns an iterator object that produces
a two element array-like object whose first
element is a value that will be used as a Map key and whose second element is the
value to associate with that key.
24.1.1.2 AddEntriesFromIterable ( target ,
iterable , adder )
The abstract operation AddEntriesFromIterable takes arguments target (an Object),
iterable (an ECMAScript language value , but
not undefined or null ), and adder (a
function
object ) and returns either a normal completion
containing an ECMAScript language
value or a throw
completion . adder will be invoked, with target
as the receiver. It performs the following steps when called:
Let iteratorRecord be ? GetIterator (iterable ,
sync ).
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , return target .
If next is not an Object , then
Let error be ThrowCompletion (a
newly created TypeError object).
Return ? IteratorClose (iteratorRecord ,
error ).
Let k be Completion (Get (next ,
"0" )).
IfAbruptCloseIterator (k ,
iteratorRecord ).
Let v be Completion (Get (next ,
"1" )).
IfAbruptCloseIterator (v ,
iteratorRecord ).
Let status be Completion (Call (adder ,
target , « k , v »)).
IfAbruptCloseIterator (status ,
iteratorRecord ).
Note
The parameter iterable is expected to be an object that implements a
%Symbol.iterator% method that
returns an iterator object that produces
a two element array-like object whose first
element is a value that will be used as a Map key and whose second element is the
value to associate with that key.
24.1.2 Properties of the Map Constructor
The Map constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
24.1.2.1 Map.groupBy ( items , callback )
Note
callback should be a function that accepts two arguments.
groupBy calls callback once for each element in
items , in ascending order, and constructs a new Map. Each value returned
by callback is used as a key in the Map. For each such key, the result
Map has an entry whose key is that key and whose value is an array containing all
the elements for which callback returned that key.
callback is called with two arguments: the value of the element and the
index of the element.
The return value of groupBy is a Map.
This function performs the following steps when called:
Let groups be ? GroupBy (items ,
callback , collection ).
Let map be ! Construct (%Map% ).
For each Record { [[Key]] , [[Elements]] }
g of groups , do
Let elements be CreateArrayFromList (g .[[Elements]] ).
Let entry be the Record
{ [[Key]] : g .[[Key]] , [[Value]] :
elements }.
Append entry to map .[[MapData]] .
Return map .
24.1.2.2 Map.prototype
The initial value of Map.prototype is the Map prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
24.1.2.3 get Map [ %Symbol.species% ]
Map[%Symbol.species%] is an accessor property whose set accessor function
is undefined . Its get accessor function performs the following steps when
called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
Methods that create derived collection objects should call %Symbol.species% to determine
the constructor to use to create the derived
objects. Subclass constructor may over-ride %Symbol.species% to change the
default constructor assignment.
24.1.3 Properties of the Map Prototype Object
The Map prototype object :
24.1.3.1 Map.prototype.clear ( )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
Set p .[[Key]] to
empty .
Set p .[[Value]] to
empty .
Return undefined .
Note
The existing [[MapData]] List is
preserved because there may be existing Map Iterator
objects that are suspended midway through iterating over that
List .
24.1.3.2 Map.prototype.constructor
The initial value of Map.prototype.constructor is %Map% .
24.1.3.3 Map.prototype.delete ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
Set key to CanonicalizeKeyedCollectionKey (key ).
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
then
Set p .[[Key]] to
empty .
Set p .[[Value]] to
empty .
Return true .
Return false .
Note
The value empty is used as a specification device to indicate
that an entry has been deleted. Actual implementations may take other actions such
as physically removing the entry from internal data structures.
24.1.3.4 Map.prototype.entries ( )
This method performs the following steps when called:
Let M be the this value.
Return ? CreateMapIterator (M ,
key+value ).
24.1.3.5 Map.prototype.forEach ( callback [ ,
thisArg ] )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let entries be M .[[MapData]] .
Let numEntries be the number of elements in entries .
Let index be 0.
Repeat, while index < numEntries ,
Let e be entries [index ].
Set index to index + 1.
If e .[[Key]] is not
empty , then
Perform ? Call (callback ,
thisArg , « e .[[Value]] , e .[[Key]] , M »).
NOTE: The number of elements in entries may have
increased during execution of callback .
Set numEntries to the number of elements in
entries .
Return undefined .
Note
callback should be a function that accepts three arguments.
forEach calls callback once for each key/value pair present
in the Map, in key insertion order. callback is called only for keys of
the Map which actually exist; it is not called for keys that have been deleted from
the Map.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the value of the item, the key of
the item, and the Map being traversed.
forEach does not directly mutate the object on which it is called but
the object may be mutated by the calls to callback . Each entry of a map's
[[MapData]] is only visited once. New keys added after the
call to forEach begins are visited. A key will be revisited if it is
deleted after it has been visited and then re-added before the forEach
call completes. Keys that are deleted after the call to forEach begins
and before being visited are not visited unless the key is added again before the
forEach call completes.
24.1.3.6 Map.prototype.get ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
Set key to CanonicalizeKeyedCollectionKey (key ).
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
return p .[[Value]] .
Return undefined .
24.1.3.7 Map.prototype.has ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
Set key to CanonicalizeKeyedCollectionKey (key ).
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
return true .
Return false .
24.1.3.8 Map.prototype.keys ( )
This method performs the following steps when called:
Let M be the this value.
Return ? CreateMapIterator (M ,
key ).
24.1.3.9 Map.prototype.set ( key , value )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
Set key to CanonicalizeKeyedCollectionKey (key ).
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
then
Set p .[[Value]] to
value .
Return M .
Let p be the Record { [[Key]] : key , [[Value]] :
value }.
Append p to M .[[MapData]] .
Return M .
24.1.3.10 get Map.prototype.size
Map.prototype.size is an accessor property whose set accessor function
is undefined . Its get accessor function performs the following steps when
called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[MapData]] ).
Let count be 0.
For each Record { [[Key]] , [[Value]] }
p of M .[[MapData]] , do
If p .[[Key]] is not
empty , set count to count + 1.
Return 𝔽 (count ).
24.1.3.11 Map.prototype.values ( )
This method performs the following steps when called:
Let M be the this value.
Return ? CreateMapIterator (M ,
value ).
24.1.3.12 Map.prototype [ %Symbol.iterator% ] ( )
The initial value of the %Symbol.iterator% property is
%Map.prototype.entries%, defined in 24.1.3.4 .
24.1.3.13 Map.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Map" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
24.1.4 Properties of Map Instances
Map instances are ordinary objects that inherit properties from the
Map prototype object .
Map instances also have a [[MapData]] internal slot.
24.1.5 Map Iterator Objects
A Map
Iterator is an object that represents a specific iteration over some specific Map
instance object. There is not a named constructor for Map Iterator objects. Instead, Map
Iterator objects are created by calling certain methods of Map instance objects.
24.1.5.1 CreateMapIterator ( map , kind )
The abstract operation CreateMapIterator takes arguments map (an ECMAScript language value ) and
kind (key+value , key , or
value ) and returns either a normal completion
containing a Generator or a throw completion . It
is used to create iterator objects for Map methods that
return such iterators . It performs the following
steps when called:
Perform ? RequireInternalSlot (map ,
[[MapData]] ).
Let closure be a new Abstract Closure
with no parameters that captures map and kind and performs the
following steps when called:
Let entries be map .[[MapData]] .
Let index be 0.
Let numEntries be the number of elements in entries .
Repeat, while index < numEntries ,
Let e be entries [index ].
Set index to index + 1.
If e .[[Key]] is not
empty , then
If kind is key , then
Let result be e .[[Key]] .
Else if kind is value ,
then
Let result be e .[[Value]] .
Else,
Assert :
kind is key+value .
Let result be CreateArrayFromList («
e .[[Key]] ,
e .[[Value]] »).
Perform ? GeneratorYield (CreateIteratorResultObject (result ,
false )).
NOTE: The number of elements in entries may have
increased while execution of this abstract operation was
paused by GeneratorYield .
Set numEntries to the number of elements in
entries .
Return NormalCompletion (unused ).
Return CreateIteratorFromClosure (closure ,
"%MapIteratorPrototype%" , %MapIteratorPrototype% ).
24.1.5.2 The %MapIteratorPrototype% Object
The %MapIteratorPrototype% object:
24.1.5.2.1 %MapIteratorPrototype%.next ( )
Return ? GeneratorResume (this
value, empty ,
"%MapIteratorPrototype%" ).
24.1.5.2.2 %MapIteratorPrototype% [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is
the String value "Map Iterator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
24.2 Set Objects
Set objects are collections of ECMAScript language values . A distinct
value may only occur once as an element of a Set's collection. Distinct values are discriminated
using the semantics of the SameValueZero comparison algorithm.
Set objects must be implemented using either hash tables or other mechanisms that, on average,
provide access times that are sublinear on the number of elements in the collection. The data
structure used in this specification is only intended to describe the required observable semantics
of Set objects. It is not intended to be a viable implementation model.
24.2.1 Abstract Operations For Set Objects
24.2.1.1 Set Records
A Set Record is a Record value used to
encapsulate the interface of a Set or similar object.
Set Records have the fields listed in Table 76 .
Table 76: Set Record Fields
Field Name
Value
Meaning
[[SetObject]]
an Object
the Set or similar object.
[[Size]]
a non-negative integer or +∞
The reported size of the object.
[[Has]]
a function object
The has method of the object.
[[Keys]]
a function object
The keys method of the object.
24.2.1.2 GetSetRecord ( obj )
The abstract operation GetSetRecord takes argument obj (an ECMAScript language value ) and
returns either a normal completion
containing a Set Record or a throw completion . It
performs the following steps when called:
If obj is not an Object , throw a
TypeError exception.
Let rawSize be ? Get (obj ,
"size" ).
Let numSize be ? ToNumber (rawSize ).
NOTE: If rawSize is undefined , then numSize
will be NaN .
If numSize is NaN , throw a
TypeError exception.
Let intSize be ! ToIntegerOrInfinity (numSize ).
If intSize < 0, throw a RangeError exception.
Let has be ? Get (obj ,
"has" ).
If IsCallable (has ) is
false , throw a TypeError exception.
Let keys be ? Get (obj ,
"keys" ).
If IsCallable (keys ) is
false , throw a TypeError exception.
Return a new Set Record { [[SetObject]] : obj , [[Size]] : intSize , [[Has]] : has , [[Keys]] :
keys }.
24.2.1.3 SetDataHas ( setData , value )
The abstract operation SetDataHas takes arguments setData (a List of either
ECMAScript language values or
empty ) and value (an ECMAScript language value ) and
returns a Boolean. It performs the following steps when called:
If SetDataIndex (setData ,
value ) is not-found , return
false .
Return true .
24.2.1.4 SetDataIndex ( setData , value )
The abstract operation SetDataIndex takes arguments setData (a List of either
ECMAScript language values or
empty ) and value (an ECMAScript language value ) and
returns a non-negative integer or not-found . It
performs the following steps when called:
Set value to CanonicalizeKeyedCollectionKey (value ).
Let size be the number of elements in setData .
Let index be 0.
Repeat, while index < size ,
Let e be setData [index ].
If e is not empty and e is
value , then
Return index .
Set index to index + 1.
Return not-found .
24.2.1.5 SetDataSize ( setData )
The abstract operation SetDataSize takes argument setData (a List of either
ECMAScript language values or
empty ) and returns a non-negative integer . It performs the following
steps when called:
Let count be 0.
For each element e of setData , do
If e is not empty , set count to
count + 1.
Return count .
24.2.2 The Set Constructor
The Set constructor :
is %Set% .
is the initial value of the "Set" property of the global
object .
creates and initializes a new Set object when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Set behaviour must include a super call to the Set constructor to
create and initialize the subclass instance with the internal state necessary to support the
Set.prototype built-in methods.
24.2.2.1 Set ( [ iterable ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let set be ? OrdinaryCreateFromConstructor (NewTarget,
"%Set.prototype%" , « [[SetData]] »).
Set set .[[SetData]] to a new empty List .
If iterable is either undefined or
null , return set .
Let adder be ? Get (set ,
"add" ).
If IsCallable (adder ) is
false , throw a TypeError exception.
Let iteratorRecord be ? GetIterator (iterable ,
sync ).
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , return set .
Let status be Completion (Call (adder ,
set , « next »)).
IfAbruptCloseIterator (status ,
iteratorRecord ).
24.2.3 Properties of the Set Constructor
The Set constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
24.2.3.1 Set.prototype
The initial value of Set.prototype is the Set prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
24.2.3.2 get Set [ %Symbol.species% ]
Set[%Symbol.species%] is an accessor property whose set accessor function
is undefined . Its get accessor function performs the following steps when
called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
Methods that create derived collection objects should call %Symbol.species% to determine
the constructor to use to create the derived
objects. Subclass constructor may over-ride %Symbol.species% to change the
default constructor assignment.
24.2.4 Properties of the Set Prototype Object
The Set prototype object :
24.2.4.1 Set.prototype.add ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
Set value to CanonicalizeKeyedCollectionKey (value ).
For each element e of S .[[SetData]] ,
do
If e is not empty and SameValue (e ,
value ) is true , then
Return S .
Append value to S .[[SetData]] .
Return S .
24.2.4.2 Set.prototype.clear ( )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
For each element e of S .[[SetData]] ,
do
Replace the element of S .[[SetData]]
whose value is e with an element whose value is
empty .
Return undefined .
Note
The existing [[SetData]] List is
preserved because there may be existing Set Iterator
objects that are suspended midway through iterating over that
List .
24.2.4.3 Set.prototype.constructor
The initial value of Set.prototype.constructor is %Set% .
24.2.4.4 Set.prototype.delete ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
Set value to CanonicalizeKeyedCollectionKey (value ).
For each element e of S .[[SetData]] ,
do
If e is not empty and SameValue (e ,
value ) is true , then
Replace the element of S .[[SetData]] whose value is e with
an element whose value is empty .
Return true .
Return false .
Note
The value empty is used as a specification device to indicate
that an entry has been deleted. Actual implementations may take other actions such
as physically removing the entry from internal data structures.
24.2.4.5 Set.prototype.difference ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
Let resultSetData be a copy of O .[[SetData]] .
If SetDataSize (O .[[SetData]] ) ≤ otherRec .[[Size]] , then
Let thisSize be the number of elements in O .[[SetData]] .
Let index be 0.
Repeat, while index < thisSize ,
Let e be resultSetData [index ].
If e is not empty , then
Let inOther be ToBoolean (?
Call (otherRec .[[Has]] , otherRec .[[SetObject]] , «
e »)).
If inOther is true , then
Set resultSetData [index ] to
empty .
Set index to index + 1.
Else,
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
Set next to CanonicalizeKeyedCollectionKey (next ).
Let valueIndex be SetDataIndex (resultSetData ,
next ).
If valueIndex is not
not-found , then
Set resultSetData [valueIndex ]
to empty .
Let result be OrdinaryObjectCreate (%Set.prototype% ,
« [[SetData]] »).
Set result .[[SetData]] to
resultSetData .
Return result .
24.2.4.6 Set.prototype.entries ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateSetIterator (S ,
key+value ).
Note
For iteration purposes, a Set appears similar to a Map where each entry has the same
value for its key and value.
24.2.4.7 Set.prototype.forEach ( callback [ ,
thisArg ] )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
If IsCallable (callback ) is
false , throw a TypeError exception.
Let entries be S .[[SetData]] .
Let numEntries be the number of elements in entries .
Let index be 0.
Repeat, while index < numEntries ,
Let e be entries [index ].
Set index to index + 1.
If e is not empty , then
Perform ? Call (callback ,
thisArg , « e , e ,
S »).
NOTE: The number of elements in entries may have
increased during execution of callback .
Set numEntries to the number of elements in
entries .
Return undefined .
Note
callback should be a function that accepts three arguments.
forEach calls callback once for each value present in the
Set object, in value insertion order. callback is called only for values
of the Set which actually exist; it is not called for keys that have been deleted
from the set.
If a thisArg parameter is provided, it will be used as the
this value for each invocation of callback . If it is
not provided, undefined is used instead.
callback is called with three arguments: the first two arguments are a
value contained in the Set. The same value is passed for both arguments. The Set
object being traversed is passed as the third argument.
The callback is called with three arguments to be consistent with the call
back functions used by forEach methods for Map and Array. For Sets,
each item value is considered to be both the key and the value.
forEach does not directly mutate the object on which it is called but
the object may be mutated by the calls to callback .
Each value is normally visited only once. However, a value will be revisited if it is
deleted after it has been visited and then re-added before the forEach
call completes. Values that are deleted after the call to forEach
begins and before being visited are not visited unless the value is added again
before the forEach call completes. New values added after the call to
forEach begins are visited.
24.2.4.8 Set.prototype.has ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
Set value to CanonicalizeKeyedCollectionKey (value ).
For each element e of S .[[SetData]] ,
do
If e is not empty and SameValue (e ,
value ) is true , return
true .
Return false .
24.2.4.9 Set.prototype.intersection ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
Let resultSetData be a new empty List .
If SetDataSize (O .[[SetData]] ) ≤ otherRec .[[Size]] , then
Let thisSize be the number of elements in O .[[SetData]] .
Let index be 0.
Repeat, while index < thisSize ,
Let e be O .[[SetData]] [index ].
Set index to index + 1.
If e is not empty , then
Let inOther be ToBoolean (?
Call (otherRec .[[Has]] , otherRec .[[SetObject]] , «
e »)).
If inOther is true , then
NOTE: It is possible for earlier calls to
otherRec .[[Has]]
to remove and re-add an element of O .[[SetData]] , which can cause
the same element to be visited twice during this
iteration.
If SetDataHas (resultSetData ,
e ) is false , then
Append e to
resultSetData .
NOTE: The number of elements in O .[[SetData]] may have increased
during execution of otherRec .[[Has]] .
Set thisSize to the number of elements in
O .[[SetData]] .
Else,
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
Set next to CanonicalizeKeyedCollectionKey (next ).
Let inThis be SetDataHas (O .[[SetData]] , next ).
If inThis is true , then
NOTE: Because other is an arbitrary
object, it is possible for its
"keys" iterator
to produce the same value more than once.
If SetDataHas (resultSetData ,
next ) is false , then
Append next to
resultSetData .
Let result be OrdinaryObjectCreate (%Set.prototype% ,
« [[SetData]] »).
Set result .[[SetData]] to
resultSetData .
Return result .
24.2.4.10 Set.prototype.isDisjointFrom ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
If SetDataSize (O .[[SetData]] ) ≤ otherRec .[[Size]] , then
Let thisSize be the number of elements in O .[[SetData]] .
Let index be 0.
Repeat, while index < thisSize ,
Let e be O .[[SetData]] [index ].
Set index to index + 1.
If e is not empty , then
Let inOther be ToBoolean (?
Call (otherRec .[[Has]] , otherRec .[[SetObject]] , «
e »)).
If inOther is true , return
false .
NOTE: The number of elements in O .[[SetData]] may have increased
during execution of otherRec .[[Has]] .
Set thisSize to the number of elements in
O .[[SetData]] .
Else,
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
If SetDataHas (O .[[SetData]] , next ) is
true , then
Perform ? IteratorClose (keysIter ,
NormalCompletion (unused )).
Return false .
Return true .
24.2.4.11 Set.prototype.isSubsetOf ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
If SetDataSize (O .[[SetData]] ) > otherRec .[[Size]] , return false .
Let thisSize be the number of elements in O .[[SetData]] .
Let index be 0.
Repeat, while index < thisSize ,
Let e be O .[[SetData]] [index ].
Set index to index + 1.
If e is not empty , then
Let inOther be ToBoolean (? Call (otherRec .[[Has]] , otherRec .[[SetObject]] , « e »)).
If inOther is false , return
false .
NOTE: The number of elements in O .[[SetData]] may have increased during
execution of otherRec .[[Has]] .
Set thisSize to the number of elements in
O .[[SetData]] .
Return true .
24.2.4.12 Set.prototype.isSupersetOf ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
If SetDataSize (O .[[SetData]] ) < otherRec .[[Size]] , return false .
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
If SetDataHas (O .[[SetData]] , next ) is
false , then
Perform ? IteratorClose (keysIter ,
NormalCompletion (unused )).
Return false .
Return true .
24.2.4.13 Set.prototype.keys ( )
The initial value of the "keys" property is %Set.prototype.values%,
defined in 24.2.4.17 .
Note
For iteration purposes, a Set appears similar to a Map where each entry has the same
value for its key and value.
24.2.4.14 get Set.prototype.size
Set.prototype.size is an accessor property whose set accessor function
is undefined . Its get accessor function performs the following steps when
called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[SetData]] ).
Let size be SetDataSize (S .[[SetData]] ).
Return 𝔽 (size ).
24.2.4.15 Set.prototype.symmetricDifference ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let resultSetData be a copy of O .[[SetData]] .
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
Set next to CanonicalizeKeyedCollectionKey (next ).
Let resultIndex be SetDataIndex (resultSetData ,
next ).
If resultIndex is not-found , let
alreadyInResult be false ; otherwise
let alreadyInResult be true .
If SetDataHas (O .[[SetData]] , next ) is
true , then
If alreadyInResult is true ,
set resultSetData [resultIndex ] to
empty .
Else,
If alreadyInResult is false ,
append next to resultSetData .
Let result be OrdinaryObjectCreate (%Set.prototype% ,
« [[SetData]] »).
Set result .[[SetData]] to
resultSetData .
Return result .
24.2.4.16 Set.prototype.union ( other )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[SetData]] ).
Let otherRec be ? GetSetRecord (other ).
Let keysIter be ? GetIteratorFromMethod (otherRec .[[SetObject]] , otherRec .[[Keys]] ).
Let resultSetData be a copy of O .[[SetData]] .
Let next be not-started .
Repeat, while next is not done ,
Set next to ? IteratorStepValue (keysIter ).
If next is not done , then
Set next to CanonicalizeKeyedCollectionKey (next ).
If SetDataHas (resultSetData ,
next ) is false , then
Append next to resultSetData .
Let result be OrdinaryObjectCreate (%Set.prototype% ,
« [[SetData]] »).
Set result .[[SetData]] to
resultSetData .
Return result .
24.2.4.17 Set.prototype.values ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateSetIterator (S ,
value ).
24.2.4.18 Set.prototype [ %Symbol.iterator% ] ( )
The initial value of the %Symbol.iterator% property is
%Set.prototype.values%, defined in 24.2.4.17 .
24.2.4.19 Set.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Set" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
24.2.5 Properties of Set Instances
Set instances are ordinary objects that inherit properties from the
Set prototype object .
Set instances also have a [[SetData]] internal slot.
24.2.6 Set Iterator Objects
A Set
Iterator is an ordinary object , with the structure defined
below, that represents a specific iteration over some specific Set instance object. There is not
a named constructor for Set Iterator objects. Instead, Set
Iterator objects are created by calling certain methods of Set instance objects.
24.2.6.1 CreateSetIterator ( set , kind )
The abstract operation CreateSetIterator takes arguments set (an ECMAScript language value ) and
kind (key+value or value ) and
returns either a normal completion
containing a Generator or a throw completion . It
is used to create iterator objects for Set methods that
return such iterators . It performs the following
steps when called:
Perform ? RequireInternalSlot (set ,
[[SetData]] ).
Let closure be a new Abstract Closure
with no parameters that captures set and kind and performs the
following steps when called:
Let index be 0.
Let entries be set .[[SetData]] .
Let numEntries be the number of elements in entries .
Repeat, while index < numEntries ,
Let e be entries [index ].
Set index to index + 1.
If e is not empty , then
If kind is key+value , then
Let result be CreateArrayFromList («
e , e »).
Perform ? GeneratorYield (CreateIteratorResultObject (result ,
false )).
Else,
Assert :
kind is value .
Perform ? GeneratorYield (CreateIteratorResultObject (e ,
false )).
NOTE: The number of elements in entries may have
increased while execution of this abstract operation was
paused by GeneratorYield .
Set numEntries to the number of elements in
entries .
Return NormalCompletion (unused ).
Return CreateIteratorFromClosure (closure ,
"%SetIteratorPrototype%" , %SetIteratorPrototype% ).
24.2.6.2 The %SetIteratorPrototype% Object
The %SetIteratorPrototype% object:
24.2.6.2.1 %SetIteratorPrototype%.next ( )
Return ? GeneratorResume (this
value, empty ,
"%SetIteratorPrototype%" ).
24.2.6.2.2 %SetIteratorPrototype% [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is
the String value "Set Iterator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
24.3 WeakMap Objects
WeakMaps are collections of key/value pairs where the keys are objects and/or symbols and values may
be arbitrary ECMAScript language values . A WeakMap
may be queried to see if it contains a key/value pair with a specific key, but no mechanism is
provided for enumerating the values it holds as keys. In certain conditions, values which are not
live are
removed as WeakMap keys, as described in 9.9.3 .
An implementation may impose an arbitrarily determined latency between the time a key/value pair of a
WeakMap becomes inaccessible and the time when the key/value pair is removed from the WeakMap. If
this latency was observable to ECMAScript program, it would be a source of indeterminacy that could
impact program execution. For that reason, an ECMAScript implementation must not provide any means
to observe a key of a WeakMap that does not require the observer to present the observed key.
WeakMaps must be implemented using either hash tables or other mechanisms that, on average, provide
access times that are sublinear on the number of key/value pairs in the collection. The data
structure used in this specification is only intended to describe the required observable semantics
of WeakMaps. It is not intended to be a viable implementation model.
Note
WeakMap and WeakSet are intended to provide mechanisms for dynamically associating state with
an object or symbol in a manner that does not “leak” memory resources if, in the absence of
the WeakMap or WeakSet instance, the object or symbol otherwise became inaccessible and
subject to resource reclamation by the implementation's garbage collection mechanisms. This
characteristic can be achieved by using an inverted per-object/symbol mapping of WeakMap or
WeakSet instances to keys. Alternatively, each WeakMap or WeakSet instance may internally
store its key and value data, but this approach requires coordination between the WeakMap or
WeakSet implementation and the garbage collector. The following references describe
mechanism that may be useful to implementations of WeakMap and WeakSet:
Barry Hayes. 1997. Ephemerons: a new finalization mechanism. In Proceedings of the 12th
ACM SIGPLAN conference on Object-oriented programming, systems, languages, and
applications (OOPSLA '97) , A. Michael Berman (Ed.). ACM, New York, NY, USA, 176-183,
http://doi.acm.org/10.1145/263698.263733 .
Alexandra Barros, Roberto Ierusalimschy, Eliminating Cycles in Weak Tables. Journal of
Universal Computer Science - J.UCS, vol. 14, no. 21, pp. 3481-3497, 2008, http://www.jucs.org/jucs_14_21/eliminating_cycles_in_weak
24.3.1 The WeakMap Constructor
The WeakMap constructor :
is %WeakMap% .
is the initial value of the "WeakMap" property of the global
object .
creates and initializes a new WeakMap when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
WeakMap behaviour must include a super call to the WeakMap constructor to
create and initialize the subclass instance with the internal state necessary to support the
WeakMap.prototype built-in methods.
24.3.1.1 WeakMap ( [ iterable ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let map be ? OrdinaryCreateFromConstructor (NewTarget,
"%WeakMap.prototype%" , « [[WeakMapData]] »).
Set map .[[WeakMapData]] to a new empty List .
If iterable is either undefined or
null , return map .
Let adder be ? Get (map ,
"set" ).
If IsCallable (adder ) is
false , throw a TypeError exception.
Return ? AddEntriesFromIterable (map ,
iterable , adder ).
Note
If the parameter iterable is present, it is expected to be an object that
implements a %Symbol.iterator% method that
returns an iterator object that produces
a two element array-like object whose first
element is a value that will be used as a WeakMap key and whose second element is
the value to associate with that key.
24.3.2 Properties of the WeakMap Constructor
The WeakMap constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
24.3.2.1 WeakMap.prototype
The initial value of WeakMap.prototype is the WeakMap prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
24.3.3 Properties of the WeakMap Prototype Object
The WeakMap prototype object :
24.3.3.1 WeakMap.prototype.constructor
The initial value of WeakMap.prototype.constructor is %WeakMap% .
24.3.3.2 WeakMap.prototype.delete ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[WeakMapData]] ).
If CanBeHeldWeakly (key )
is false , return false .
For each Record { [[Key]] , [[Value]] }
p of M .[[WeakMapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
then
Set p .[[Key]] to
empty .
Set p .[[Value]] to
empty .
Return true .
Return false .
Note
The value empty is used as a specification device to indicate
that an entry has been deleted. Actual implementations may take other actions such
as physically removing the entry from internal data structures.
24.3.3.3 WeakMap.prototype.get ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[WeakMapData]] ).
If CanBeHeldWeakly (key )
is false , return undefined .
For each Record { [[Key]] , [[Value]] }
p of M .[[WeakMapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
return p .[[Value]] .
Return undefined .
24.3.3.4 WeakMap.prototype.has ( key )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[WeakMapData]] ).
If CanBeHeldWeakly (key )
is false , return false .
For each Record { [[Key]] , [[Value]] }
p of M .[[WeakMapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
return true .
Return false .
24.3.3.5 WeakMap.prototype.set ( key ,
value )
This method performs the following steps when called:
Let M be the this value.
Perform ? RequireInternalSlot (M ,
[[WeakMapData]] ).
If CanBeHeldWeakly (key )
is false , throw a TypeError exception.
For each Record { [[Key]] , [[Value]] }
p of M .[[WeakMapData]] , do
If p .[[Key]] is not
empty and SameValue (p .[[Key]] , key ) is true ,
then
Set p .[[Value]] to
value .
Return M .
Let p be the Record { [[Key]] : key , [[Value]] :
value }.
Append p to M .[[WeakMapData]] .
Return M .
24.3.3.6 WeakMap.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "WeakMap" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
24.3.4 Properties of WeakMap Instances
WeakMap instances are ordinary objects that inherit properties from the
WeakMap prototype
object . WeakMap instances also have a [[WeakMapData]] internal slot.
24.4 WeakSet Objects
WeakSets are collections of objects and/or symbols. A distinct object or symbol may only occur once
as an element of a WeakSet's collection. A WeakSet may be queried to see if it contains a specific
value, but no mechanism is provided for enumerating the values it holds. In certain conditions,
values which are not live are removed as WeakSet elements, as described in
9.9.3 .
An implementation may impose an arbitrarily determined latency between the time a value contained in
a WeakSet becomes inaccessible and the time when the value is removed from the WeakSet. If this
latency was observable to ECMAScript program, it would be a source of indeterminacy that could
impact program execution. For that reason, an ECMAScript implementation must not provide any means
to determine if a WeakSet contains a particular value that does not require the observer to present
the observed value.
WeakSets must be implemented using either hash tables or other mechanisms that, on average, provide
access times that are sublinear on the number of elements in the collection. The data structure used
in this specification is only intended to describe the required observable semantics of WeakSets. It
is not intended to be a viable implementation model.
Note
24.4.1 The WeakSet Constructor
The WeakSet constructor :
is %WeakSet% .
is the initial value of the "WeakSet" property of the global
object .
creates and initializes a new WeakSet when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
WeakSet behaviour must include a super call to the WeakSet constructor to
create and initialize the subclass instance with the internal state necessary to support the
WeakSet.prototype built-in methods.
24.4.1.1 WeakSet ( [ iterable ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let set be ? OrdinaryCreateFromConstructor (NewTarget,
"%WeakSet.prototype%" , « [[WeakSetData]] »).
Set set .[[WeakSetData]] to a new empty List .
If iterable is either undefined or
null , return set .
Let adder be ? Get (set ,
"add" ).
If IsCallable (adder ) is
false , throw a TypeError exception.
Let iteratorRecord be ? GetIterator (iterable ,
sync ).
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , return set .
Let status be Completion (Call (adder ,
set , « next »)).
IfAbruptCloseIterator (status ,
iteratorRecord ).
24.4.2 Properties of the WeakSet Constructor
The WeakSet constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
24.4.2.1 WeakSet.prototype
The initial value of WeakSet.prototype is the WeakSet prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
24.4.3 Properties of the WeakSet Prototype Object
The WeakSet prototype object :
24.4.3.1 WeakSet.prototype.add ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[WeakSetData]] ).
If CanBeHeldWeakly (value )
is false , throw a TypeError exception.
For each element e of S .[[WeakSetData]] , do
If e is not empty and SameValue (e ,
value ) is true , then
Return S .
Append value to S .[[WeakSetData]] .
Return S .
24.4.3.2 WeakSet.prototype.constructor
The initial value of WeakSet.prototype.constructor is %WeakSet% .
24.4.3.3 WeakSet.prototype.delete ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[WeakSetData]] ).
If CanBeHeldWeakly (value )
is false , return false .
For each element e of S .[[WeakSetData]] , do
If e is not empty and SameValue (e ,
value ) is true , then
Replace the element of S .[[WeakSetData]] whose value is e
with an element whose value is empty .
Return true .
Return false .
Note
The value empty is used as a specification device to indicate
that an entry has been deleted. Actual implementations may take other actions such
as physically removing the entry from internal data structures.
24.4.3.4 WeakSet.prototype.has ( value )
This method performs the following steps when called:
Let S be the this value.
Perform ? RequireInternalSlot (S ,
[[WeakSetData]] ).
If CanBeHeldWeakly (value )
is false , return false .
For each element e of S .[[WeakSetData]] , do
If e is not empty and SameValue (e ,
value ) is true , return
true .
Return false .
24.4.3.5 WeakSet.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "WeakSet" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
24.4.4 Properties of WeakSet Instances
WeakSet instances are ordinary objects that inherit properties from the
WeakSet prototype
object . WeakSet instances also have a [[WeakSetData]] internal slot.
24.5 Abstract Operations for Keyed Collections
24.5.1 CanonicalizeKeyedCollectionKey ( key )
The abstract operation CanonicalizeKeyedCollectionKey takes argument key (an ECMAScript language value ) and
returns an ECMAScript language value . It
performs the following steps when called:
If key is -0 𝔽 , return
+0 𝔽 .
Return key .
25 Structured Data
25.1 ArrayBuffer Objects
25.1.1 Notation
The descriptions below in this section, 25.4 , and 29 use the read-modify-write
modification function internal data structure.
A read-modify-write
modification function is a mathematical function that is represented as an abstract
closure that takes two Lists of
byte
values as arguments and returns a List of byte
values . These abstract closures satisfy all of the following properties:
They perform all their algorithm steps atomically.
Their individual algorithm steps are not observable.
Note
To aid verifying that a read-modify-write modification function's algorithm steps
constitute a pure, mathematical function, the following editorial conventions are
recommended:
25.1.2 Fixed-length and Resizable ArrayBuffer Objects
A fixed-length ArrayBuffer is an ArrayBuffer whose byte length cannot
change after creation.
A resizable ArrayBuffer is an ArrayBuffer whose byte length may change
after creation via calls to ArrayBuffer.prototype.resize (
newLength ) .
The kind of ArrayBuffer object that is created depends on the arguments passed to ArrayBuffer ( length [ , options ]
) .
25.1.3 Abstract Operations For ArrayBuffer Objects
25.1.3.1 AllocateArrayBuffer ( constructor ,
byteLength [ , maxByteLength ] )
The abstract operation AllocateArrayBuffer takes arguments constructor (a
constructor ) and byteLength (a
non-negative integer ) and optional argument
maxByteLength (a non-negative integer or empty ) and returns
either a normal completion
containing an ArrayBuffer or a throw completion . It
is used to create an ArrayBuffer. It performs the following steps when called:
Let slots be « [[ArrayBufferData]] , [[ArrayBufferByteLength]] , [[ArrayBufferDetachKey]] ».
If maxByteLength is present and maxByteLength is not
empty , let allocatingResizableBuffer be
true ; otherwise let allocatingResizableBuffer be
false .
If allocatingResizableBuffer is true , then
If byteLength > maxByteLength , throw a
RangeError exception.
Append [[ArrayBufferMaxByteLength]] to
slots .
Let obj be ? OrdinaryCreateFromConstructor (constructor ,
"%ArrayBuffer.prototype%" , slots ).
Let block be ? CreateByteDataBlock (byteLength ).
Set obj .[[ArrayBufferData]] to block .
Set obj .[[ArrayBufferByteLength]] to
byteLength .
If allocatingResizableBuffer is true , then
If it is not possible to create a Data Block
block consisting of maxByteLength bytes, throw a
RangeError exception.
NOTE: Resizable ArrayBuffers are designed to be implementable with in-place
growth. Implementations may throw if, for example, virtual memory cannot be
reserved up front.
Set obj .[[ArrayBufferMaxByteLength]] to
maxByteLength .
Return obj .
25.1.3.2 ArrayBufferByteLength ( arrayBuffer ,
order )
The abstract operation ArrayBufferByteLength takes arguments arrayBuffer (an
ArrayBuffer or SharedArrayBuffer) and order (seq-cst or
unordered ) and returns a non-negative integer . It performs the following
steps when called:
If IsSharedArrayBuffer (arrayBuffer )
is true and arrayBuffer has an [[ArrayBufferByteLengthData]] internal slot, then
Let bufferByteLengthBlock be arrayBuffer .[[ArrayBufferByteLengthData]] .
Let rawLength be GetRawBytesFromSharedBlock (bufferByteLengthBlock ,
0, biguint64 , true ,
order ).
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent 's
Agent
Record .
Return ℝ (RawBytesToNumeric (biguint64 ,
rawLength , isLittleEndian )).
Assert :
IsDetachedBuffer (arrayBuffer )
is false .
Return arrayBuffer .[[ArrayBufferByteLength]] .
25.1.3.3 ArrayBufferCopyAndDetach ( arrayBuffer ,
newLength , preserveResizability )
The abstract operation ArrayBufferCopyAndDetach takes arguments arrayBuffer (an
ECMAScript language value ),
newLength (an ECMAScript language value ), and
preserveResizability (preserve-resizability or
fixed-length ) and returns either a normal completion
containing an ArrayBuffer or a throw completion . It
performs the following steps when called:
Perform ? RequireInternalSlot (arrayBuffer ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (arrayBuffer )
is true , throw a TypeError exception.
If newLength is undefined , then
Let newByteLength be arrayBuffer .[[ArrayBufferByteLength]] .
Else,
Let newByteLength be ? ToIndex (newLength ).
If IsDetachedBuffer (arrayBuffer )
is true , throw a TypeError exception.
If preserveResizability is preserve-resizability
and IsFixedLengthArrayBuffer (arrayBuffer )
is false , then
Let newMaxByteLength be arrayBuffer .[[ArrayBufferMaxByteLength]] .
Else,
Let newMaxByteLength be empty .
If arrayBuffer .[[ArrayBufferDetachKey]] is not
undefined , throw a TypeError exception.
Let newBuffer be ? AllocateArrayBuffer (%ArrayBuffer% ,
newByteLength , newMaxByteLength ).
Let copyLength be min (newByteLength ,
arrayBuffer .[[ArrayBufferByteLength]] ).
Let fromBlock be arrayBuffer .[[ArrayBufferData]] .
Let toBlock be newBuffer .[[ArrayBufferData]] .
Perform CopyDataBlockBytes (toBlock ,
0, fromBlock , 0, copyLength ).
NOTE: Neither creation of the new Data Block nor copying
from the old Data Block are observable.
Implementations may implement this method as a zero-copy move or a
realloc.
Perform ! DetachArrayBuffer (arrayBuffer ).
Return newBuffer .
25.1.3.4 IsDetachedBuffer ( arrayBuffer )
The abstract operation IsDetachedBuffer takes argument arrayBuffer (an ArrayBuffer
or a SharedArrayBuffer) and returns a Boolean. It performs the following steps when called:
If arrayBuffer .[[ArrayBufferData]] is
null , return true .
Return false .
25.1.3.5 DetachArrayBuffer ( arrayBuffer [ ,
key ] )
The abstract operation DetachArrayBuffer takes argument arrayBuffer (an
ArrayBuffer) and optional argument key (anything) and returns either a normal completion
containing unused or a throw completion . It
performs the following steps when called:
Assert :
IsSharedArrayBuffer (arrayBuffer )
is false .
If key is not present, set key to
undefined .
If arrayBuffer .[[ArrayBufferDetachKey]] is not
key , throw a TypeError exception.
Set arrayBuffer .[[ArrayBufferData]] to
null .
Set arrayBuffer .[[ArrayBufferByteLength]] to 0.
Return unused .
Note
Detaching an ArrayBuffer instance disassociates the Data Block used as its
backing store from the instance and sets the byte length of the buffer to 0.
25.1.3.6 CloneArrayBuffer ( srcBuffer ,
srcByteOffset , srcLength )
The abstract operation CloneArrayBuffer takes arguments srcBuffer (an ArrayBuffer
or a SharedArrayBuffer), srcByteOffset (a non-negative integer ), and srcLength (a
non-negative integer ) and returns either a normal completion
containing an ArrayBuffer or a throw completion . It
creates a new ArrayBuffer whose data is a copy of srcBuffer 's data over the range
starting at srcByteOffset and continuing for srcLength bytes. It
performs the following steps when called:
Assert :
IsDetachedBuffer (srcBuffer )
is false .
Let targetBuffer be ? AllocateArrayBuffer (%ArrayBuffer% ,
srcLength ).
Let srcBlock be srcBuffer .[[ArrayBufferData]] .
Let targetBlock be targetBuffer .[[ArrayBufferData]] .
Perform CopyDataBlockBytes (targetBlock ,
0, srcBlock , srcByteOffset , srcLength ).
Return targetBuffer .
25.1.3.7 GetArrayBufferMaxByteLengthOption ( options
)
The abstract operation GetArrayBufferMaxByteLengthOption takes argument options
(an ECMAScript language value ) and
returns either a normal completion
containing either a non-negative integer or
empty , or a throw completion . It
performs the following steps when called:
If options is not an Object , return
empty .
Let maxByteLength be ? Get (options ,
"maxByteLength" ).
If maxByteLength is undefined , return
empty .
Return ? ToIndex (maxByteLength ).
25.1.3.8 HostResizeArrayBuffer ( buffer ,
newByteLength )
The host-defined abstract operation
HostResizeArrayBuffer takes arguments buffer (an ArrayBuffer) and
newByteLength (a non-negative integer ) and returns either a normal completion
containing either handled or
unhandled , or a throw completion . It
gives the host an
opportunity to perform implementation-defined resizing of
buffer . If the host chooses not to handle resizing of
buffer , it may return unhandled for the default behaviour.
The implementation of HostResizeArrayBuffer must conform to the following requirements:
The abstract operation does not detach buffer .
If the abstract operation completes normally with handled ,
buffer .[[ArrayBufferByteLength]] is
newByteLength .
The default implementation of HostResizeArrayBuffer is to return NormalCompletion (unhandled ).
25.1.3.9 IsFixedLengthArrayBuffer ( arrayBuffer )
The abstract operation IsFixedLengthArrayBuffer takes argument arrayBuffer (an
ArrayBuffer or a SharedArrayBuffer) and returns a Boolean. It performs the following steps
when called:
If arrayBuffer has an [[ArrayBufferMaxByteLength]] internal slot, return
false .
Return true .
25.1.3.10 IsUnsignedElementType ( type )
The abstract operation IsUnsignedElementType takes argument type (a TypedArray element type ) and returns a
Boolean. It verifies if the argument type is an unsigned TypedArray element type . It performs
the following steps when called:
If type is one of uint8 ,
uint8clamped , uint16 ,
uint32 , or biguint64 , return
true .
Return false .
25.1.3.11 IsUnclampedIntegerElementType ( type )
The abstract operation IsUnclampedIntegerElementType takes argument type (a
TypedArray element type ) and returns a
Boolean. It verifies if the argument type is an Integer TypedArray element type not including
uint8clamped . It performs the following steps when called:
If type is one of int8 ,
uint8 , int16 ,
uint16 , int32 , or
uint32 , return true .
Return false .
25.1.3.12 IsBigIntElementType ( type )
The abstract operation IsBigIntElementType takes argument type (a TypedArray element type ) and returns a
Boolean. It verifies if the argument type is a BigInt
TypedArray element type . It performs
the following steps when called:
If type is either biguint64 or
bigint64 , return true .
Return false .
25.1.3.13 IsNoTearConfiguration ( type ,
order )
The abstract operation IsNoTearConfiguration takes arguments type (a TypedArray element type ) and
order (seq-cst , unordered , or
init ) and returns a Boolean. It performs the following steps when
called:
If IsUnclampedIntegerElementType (type )
is true , return true .
If IsBigIntElementType (type )
is true and order is neither
init nor unordered , return
true .
Return false .
25.1.3.14 RawBytesToNumeric ( type ,
rawBytes , isLittleEndian )
The abstract operation RawBytesToNumeric takes arguments type (a TypedArray element type ),
rawBytes (a List of
byte
values ), and isLittleEndian (a Boolean) and returns a
Number or a BigInt. It performs the following steps when called:
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
If isLittleEndian is false , reverse the order of the
elements of rawBytes .
If type is float16 , then
Let value be the byte elements of rawBytes
concatenated and interpreted as a little-endian bit string encoding of an
IEEE 754-2019 binary16
value.
If value is a NaN, return NaN .
Return the Number value that corresponds to value .
If type is float32 , then
Let value be the byte elements of rawBytes
concatenated and interpreted as a little-endian bit string encoding of an
IEEE 754-2019 binary32
value.
If value is a NaN, return NaN .
Return the Number value that corresponds to value .
If type is float64 , then
Let value be the byte elements of rawBytes
concatenated and interpreted as a little-endian bit string encoding of an
IEEE 754-2019 binary64
value.
If value is a NaN, return NaN .
Return the Number value that corresponds to value .
If IsUnsignedElementType (type )
is true , then
Let intValue be the byte elements of rawBytes
concatenated and interpreted as a bit string encoding of an unsigned
little-endian binary number.
Else,
Let intValue be the byte elements of rawBytes
concatenated and interpreted as a bit string encoding of a binary
little-endian two's complement number of bit length elementSize ×
8.
If IsBigIntElementType (type )
is true , return the BigInt value that corresponds to
intValue .
Otherwise, return the Number value that corresponds to intValue .
25.1.3.15 GetRawBytesFromSharedBlock ( block ,
byteIndex , type , isTypedArray , order )
The abstract operation GetRawBytesFromSharedBlock takes arguments block (a
Shared Data
Block ), byteIndex (a non-negative integer ),
type (a TypedArray element type ),
isTypedArray (a Boolean), and order (seq-cst or
unordered ) and returns a List of byte
values . It performs the following steps when called:
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
Let execution be the [[CandidateExecution]]
field of the surrounding agent 's Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
If isTypedArray is true and IsNoTearConfiguration (type ,
order ) is true , let noTear be
true ; otherwise let noTear be
false .
Let rawValue be a List of length
elementSize whose elements are nondeterministically chosen byte
values .
NOTE: In implementations, rawValue is the result of a non-atomic or
atomic read instruction on the underlying hardware. The nondeterminism is a semantic
prescription of the memory model to describe observable
behaviour of hardware with weak consistency.
Let readEvent be ReadSharedMemory { [[Order]] : order , [[NoTear]] : noTear , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize }.
Append readEvent to eventsRecord .[[EventList]] .
Append Chosen Value Record { [[Event]] : readEvent , [[ChosenValue]] : rawValue } to
execution .[[ChosenValues]] .
Return rawValue .
25.1.3.16 GetValueFromBuffer ( arrayBuffer ,
byteIndex , type , isTypedArray , order [ ,
isLittleEndian ] )
The abstract operation GetValueFromBuffer takes arguments arrayBuffer (an
ArrayBuffer or SharedArrayBuffer), byteIndex (a non-negative integer ),
type (a TypedArray element type ),
isTypedArray (a Boolean), and order (seq-cst or
unordered ) and optional argument isLittleEndian (a
Boolean) and returns a Number or a BigInt. It performs the following steps when called:
Assert :
IsDetachedBuffer (arrayBuffer )
is false .
Assert :
There are sufficient bytes in arrayBuffer starting at
byteIndex to represent a value of type .
Let block be arrayBuffer .[[ArrayBufferData]] .
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
If IsSharedArrayBuffer (arrayBuffer )
is true , then
Assert : block is a
Shared Data Block .
Let rawValue be GetRawBytesFromSharedBlock (block ,
byteIndex , type , isTypedArray ,
order ).
Else,
Let rawValue be a List
whose elements are bytes from block at indices in the interval from byteIndex
(inclusive) to byteIndex + elementSize (exclusive).
Assert :
The number of elements in rawValue is elementSize .
If isLittleEndian is not present, set isLittleEndian to the
value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Return RawBytesToNumeric (type ,
rawValue , isLittleEndian ).
25.1.3.17 NumericToRawBytes ( type , value ,
isLittleEndian )
The abstract operation NumericToRawBytes takes arguments type (a TypedArray element type ),
value (a Number or a BigInt), and isLittleEndian (a Boolean) and
returns a List of byte
values . It performs the following steps when called:
If type is float16 , then
Let rawBytes be a List
whose elements are the 2 bytes that are the result of converting
value to IEEE 754-2019 binary16
format using roundTiesToEven mode. The bytes are arranged in little endian
order. If value is NaN , rawBytes
may be set to any implementation chosen IEEE 754-2019
binary16 format NaN encoding. An implementation must always choose the same
encoding for each implementation distinguishable NaN
value.
Else if type is float32 , then
Let rawBytes be a List
whose elements are the 4 bytes that are the result of converting
value to IEEE 754-2019 binary32
format using roundTiesToEven mode. The bytes are arranged in little endian
order. If value is NaN , rawBytes
may be set to any implementation chosen IEEE 754-2019
binary32 format NaN encoding. An implementation must always choose the same
encoding for each implementation distinguishable NaN
value.
Else if type is float64 , then
Let rawBytes be a List
whose elements are the 8 bytes that are the IEEE 754-2019 binary64
format encoding of value . The bytes are arranged in little endian
order. If value is NaN , rawBytes
may be set to any implementation chosen IEEE 754-2019
binary64 format NaN encoding. An implementation must always choose the same
encoding for each implementation distinguishable NaN
value.
Else,
Let n be the Element Size value specified in Table 75
for Element Type type .
Let conversionOperation be the abstract operation named in the
Conversion Operation column in Table 75
for Element Type type .
Let intValue be ℝ (!
conversionOperation (value )).
If intValue ≥ 0, then
Let rawBytes be a List
whose elements are the n -byte binary encoding of
intValue . The bytes are ordered in little endian order.
Else,
Let rawBytes be a List
whose elements are the n -byte binary two's complement
encoding of intValue . The bytes are ordered in little
endian order.
If isLittleEndian is false , reverse the order of the
elements of rawBytes .
Return rawBytes .
25.1.3.18 SetValueInBuffer ( arrayBuffer ,
byteIndex , type , value , isTypedArray ,
order [ , isLittleEndian ] )
The abstract operation SetValueInBuffer takes arguments arrayBuffer (an
ArrayBuffer or SharedArrayBuffer), byteIndex (a non-negative integer ),
type (a TypedArray element type ),
value (a Number or a BigInt), isTypedArray (a Boolean), and
order (seq-cst , unordered , or
init ) and optional argument isLittleEndian (a Boolean) and
returns unused . It performs the following steps when called:
Assert :
IsDetachedBuffer (arrayBuffer )
is false .
Assert :
There are sufficient bytes in arrayBuffer starting at
byteIndex to represent a value of type .
Assert :
value is a
BigInt if IsBigIntElementType (type )
is true ; otherwise, value is a
Number .
Let block be arrayBuffer .[[ArrayBufferData]] .
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
If isLittleEndian is not present, set isLittleEndian to the
value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Let rawBytes be NumericToRawBytes (type ,
value , isLittleEndian ).
If IsSharedArrayBuffer (arrayBuffer )
is true , then
Let execution be the [[CandidateExecution]] field of the surrounding agent 's
Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
If isTypedArray is true and IsNoTearConfiguration (type ,
order ) is true , let noTear be
true ; otherwise let noTear be
false .
Append WriteSharedMemory
{ [[Order]] : order , [[NoTear]] : noTear , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize , [[Payload]] : rawBytes } to
eventsRecord .[[EventList]] .
Else,
Store the individual bytes of rawBytes into block ,
starting at block [byteIndex ].
Return unused .
25.1.3.19 GetModifySetValueInBuffer ( arrayBuffer ,
byteIndex , type , value , op )
The abstract operation GetModifySetValueInBuffer takes arguments arrayBuffer (an
ArrayBuffer or a SharedArrayBuffer), byteIndex (a non-negative integer ),
type (a TypedArray element type ),
value (a Number or a BigInt), and op (a read-modify-write modification
function ) and returns a Number or a BigInt. It performs the following
steps when called:
Assert :
IsDetachedBuffer (arrayBuffer )
is false .
Assert :
There are sufficient bytes in arrayBuffer starting at
byteIndex to represent a value of type .
Assert :
value is a
BigInt if IsBigIntElementType (type )
is true ; otherwise, value is a
Number .
Let block be arrayBuffer .[[ArrayBufferData]] .
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Let rawBytes be NumericToRawBytes (type ,
value , isLittleEndian ).
If IsSharedArrayBuffer (arrayBuffer )
is true , then
Let execution be the [[CandidateExecution]] field of the surrounding agent 's
Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
Let rawBytesRead be a List
of length elementSize whose elements are nondeterministically
chosen byte values .
NOTE: In implementations, rawBytesRead is the result of a
load-link, of a load-exclusive, or of an operand of a read-modify-write
instruction on the underlying hardware. The nondeterminism is a semantic
prescription of the memory model to describe
observable behaviour of hardware with weak consistency.
Let rmwEvent be ReadModifyWriteSharedMemory
{ [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndex , [[ElementSize]] : elementSize , [[Payload]] : rawBytes , [[ModifyOp]] : op }.
Append rmwEvent to eventsRecord .[[EventList]] .
Append Chosen Value Record
{ [[Event]] : rmwEvent , [[ChosenValue]] : rawBytesRead } to
execution .[[ChosenValues]] .
Else,
Let rawBytesRead be a List
of length elementSize whose elements are the sequence of
elementSize bytes starting with
block [byteIndex ].
Let rawBytesModified be op (rawBytesRead ,
rawBytes ).
Store the individual bytes of rawBytesModified into
block , starting at block [byteIndex ].
Return RawBytesToNumeric (type ,
rawBytesRead , isLittleEndian ).
25.1.4 The ArrayBuffer Constructor
The ArrayBuffer constructor :
is %ArrayBuffer% .
is the initial value of the "ArrayBuffer" property of the global
object .
creates and initializes a new ArrayBuffer when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
ArrayBuffer behaviour must include a super call to the ArrayBuffer constructor to
create and initialize subclass instances with the internal state necessary to support the
ArrayBuffer.prototype built-in methods.
25.1.4.1 ArrayBuffer ( length [ , options
] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let byteLength be ? ToIndex (length ).
Let requestedMaxByteLength be ? GetArrayBufferMaxByteLengthOption (options ).
Return ? AllocateArrayBuffer (NewTarget,
byteLength , requestedMaxByteLength ).
25.1.5 Properties of the ArrayBuffer Constructor
The ArrayBuffer constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
25.1.5.1 ArrayBuffer.isView ( arg )
This function performs the following steps when called:
If arg is not an Object , return
false .
If arg has a [[ViewedArrayBuffer]] internal
slot, return true .
Return false .
25.1.5.2 ArrayBuffer.prototype
The initial value of ArrayBuffer.prototype is the ArrayBuffer prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
25.1.5.3 get ArrayBuffer [ %Symbol.species% ]
ArrayBuffer[%Symbol.species%] is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
ArrayBuffer.prototype.slice (
start , end ) normally uses its
this value's constructor to create a derived object.
However, a subclass constructor may over-ride that default
behaviour for the ArrayBuffer.prototype.slice (
start , end ) method by redefining its
%Symbol.species% property.
25.1.6 Properties of the ArrayBuffer Prototype Object
The ArrayBuffer prototype object :
is %ArrayBuffer.prototype% .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is an ordinary
object .
does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] internal slot.
25.1.6.1 get ArrayBuffer.prototype.byteLength
ArrayBuffer.prototype.byteLength is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
If IsDetachedBuffer (O )
is true , return +0 𝔽 .
Let length be O .[[ArrayBufferByteLength]] .
Return 𝔽 (length ).
25.1.6.2 ArrayBuffer.prototype.constructor
The initial value of ArrayBuffer.prototype.constructor is %ArrayBuffer% .
25.1.6.3 get ArrayBuffer.prototype.detached
ArrayBuffer.prototype.detached is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
Return IsDetachedBuffer (O ).
25.1.6.4 get ArrayBuffer.prototype.maxByteLength
ArrayBuffer.prototype.maxByteLength is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
If IsDetachedBuffer (O )
is true , return +0 𝔽 .
If IsFixedLengthArrayBuffer (O )
is true , then
Let length be O .[[ArrayBufferByteLength]] .
Else,
Let length be O .[[ArrayBufferMaxByteLength]] .
Return 𝔽 (length ).
25.1.6.5 get ArrayBuffer.prototype.resizable
ArrayBuffer.prototype.resizable is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
If IsFixedLengthArrayBuffer (O )
is false , return true ; otherwise return
false .
25.1.6.6 ArrayBuffer.prototype.resize ( newLength )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferMaxByteLength]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
Let newByteLength be ? ToIndex (newLength ).
If IsDetachedBuffer (O )
is true , throw a TypeError exception.
If newByteLength > O .[[ArrayBufferMaxByteLength]] , throw a
RangeError exception.
Let hostHandled be ? HostResizeArrayBuffer (O ,
newByteLength ).
If hostHandled is handled , return
undefined .
Let oldBlock be O .[[ArrayBufferData]] .
Let newBlock be ? CreateByteDataBlock (newByteLength ).
Let copyLength be min (newByteLength ,
O .[[ArrayBufferByteLength]] ).
Perform CopyDataBlockBytes (newBlock ,
0, oldBlock , 0, copyLength ).
NOTE: Neither creation of the new Data Block nor copying
from the old Data Block are observable.
Implementations may implement this method as in-place growth or shrinkage.
Set O .[[ArrayBufferData]] to
newBlock .
Set O .[[ArrayBufferByteLength]] to
newByteLength .
Return undefined .
25.1.6.7 ArrayBuffer.prototype.slice ( start ,
end )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is true , throw a TypeError exception.
If IsDetachedBuffer (O )
is true , throw a TypeError exception.
Let len be O .[[ArrayBufferByteLength]] .
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let first be 0.
Else if relativeStart < 0, let first be max (len
+ relativeStart , 0).
Else, let first be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let final be 0.
Else if relativeEnd < 0, let final be max (len +
relativeEnd , 0).
Else, let final be min (relativeEnd , len ).
Let newLen be max (final - first , 0).
Let ctor be ? SpeciesConstructor (O ,
%ArrayBuffer% ).
Let new be ? Construct (ctor , « 𝔽 (newLen ) »).
Perform ? RequireInternalSlot (new ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (new )
is true , throw a TypeError exception.
If IsDetachedBuffer (new )
is true , throw a TypeError exception.
If SameValue (new , O )
is true , throw a TypeError exception.
If new .[[ArrayBufferByteLength]] <
newLen , throw a TypeError exception.
NOTE: Side-effects of the above steps may have detached or resized O .
If IsDetachedBuffer (O )
is true , throw a TypeError exception.
Let fromBuf be O .[[ArrayBufferData]] .
Let toBuf be new .[[ArrayBufferData]] .
Let currentLen be O .[[ArrayBufferByteLength]] .
If first < currentLen , then
Let count be min (newLen ,
currentLen - first ).
Perform CopyDataBlockBytes (toBuf ,
0, fromBuf , first , count ).
Return new .
25.1.6.8 ArrayBuffer.prototype.transfer ( [ newLength
] )
This method performs the following steps when called:
Let O be the this value.
Return ? ArrayBufferCopyAndDetach (O ,
newLength , preserve-resizability ).
25.1.6.9 ArrayBuffer.prototype.transferToFixedLength ( [
newLength ] )
This method performs the following steps when called:
Let O be the this value.
Return ? ArrayBufferCopyAndDetach (O ,
newLength , fixed-length ).
25.1.6.10 ArrayBuffer.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "ArrayBuffer" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
25.1.7 Properties of ArrayBuffer Instances
ArrayBuffer instances inherit properties from the ArrayBuffer prototype
object . ArrayBuffer instances each have an [[ArrayBufferData]] internal slot, an [[ArrayBufferByteLength]] internal slot, and an [[ArrayBufferDetachKey]] internal slot. ArrayBuffer instances which are
resizable each have an [[ArrayBufferMaxByteLength]] internal slot.
ArrayBuffer instances whose [[ArrayBufferData]] is
null are considered to be detached and all operators to access or modify data
contained in the ArrayBuffer instance will fail.
ArrayBuffer instances whose [[ArrayBufferDetachKey]] is set to a value
other than undefined need to have all DetachArrayBuffer calls
passing that same "detach key" as an argument, otherwise a TypeError will result. This internal
slot is only ever set by certain embedding environments, not by algorithms in this
specification.
25.1.8 Resizable ArrayBuffer Guidelines
Note 1
The following are guidelines for ECMAScript programmers working with resizable
ArrayBuffer .
We recommend that programs be tested in their deployment environments where possible. The
amount of available physical memory differs greatly between hardware devices. Similarly,
virtual memory subsystems also differ greatly between hardware devices as well as
operating systems. An application that runs without out-of-memory errors on a 64-bit
desktop web browser could run out of memory on a 32-bit mobile web browser.
When choosing a value for the "maxByteLength" option for resizable
ArrayBuffer , we recommend that the smallest possible size for the
application be chosen. We recommend that "maxByteLength" does not
exceed 1,073,741,824 (230 bytes or 1GiB).
Please note that successfully constructing a resizable
ArrayBuffer for a particular maximum size does not guarantee that
future resizes will succeed.
Note 2
The following are guidelines for ECMAScript implementers implementing resizable
ArrayBuffer .
Resizable
ArrayBuffer can be implemented as copying upon resize, as
in-place growth via reserving virtual memory up front, or as a combination of both for
different values of the constructor 's
"maxByteLength" option.
If a host is
multi-tenanted (i.e. it runs many ECMAScript applications simultaneously), such as a web
browser, and its implementations choose to implement in-place growth by reserving
virtual memory, we recommend that both 32-bit and 64-bit implementations throw for
values of "maxByteLength" ≥ 1GiB to 1.5GiB. This is to reduce the
likelihood a single application can exhaust the virtual memory address space and to
reduce interoperability risk.
If a host does not
have virtual memory, such as those running on embedded devices without an MMU, or if a
host only
implements resizing by copying, it may accept any Number value
for the "maxByteLength" option. However, we
recommend a RangeError be thrown if a memory block of the requested
size can never be allocated. For example, if the requested size is greater than the
maximum amount of usable memory on the device.
25.2 SharedArrayBuffer Objects
25.2.1 Fixed-length and Growable SharedArrayBuffer Objects
A fixed-length SharedArrayBuffer is a SharedArrayBuffer whose byte
length cannot change after creation.
A growable SharedArrayBuffer is a SharedArrayBuffer whose byte length
may increase after creation via calls to SharedArrayBuffer.prototype.grow (
newLength ) .
The kind of SharedArrayBuffer object that is created depends on the arguments passed to SharedArrayBuffer ( length [ ,
options ] ) .
25.2.2 Abstract Operations for SharedArrayBuffer Objects
25.2.2.1 AllocateSharedArrayBuffer ( constructor ,
byteLength [ , maxByteLength ] )
The abstract operation AllocateSharedArrayBuffer takes arguments constructor (a
constructor ) and byteLength (a
non-negative integer ) and optional argument
maxByteLength (a non-negative integer or empty ) and returns
either a normal completion
containing a SharedArrayBuffer or a throw completion . It
is used to create a SharedArrayBuffer. It performs the following steps when called:
Let slots be « [[ArrayBufferData]] ».
If maxByteLength is present and maxByteLength is not
empty , let allocatingGrowableBuffer be
true ; otherwise let allocatingGrowableBuffer be
false .
If allocatingGrowableBuffer is true , then
If byteLength > maxByteLength , throw a
RangeError exception.
Append [[ArrayBufferByteLengthData]] and [[ArrayBufferMaxByteLength]] to slots .
Else,
Append [[ArrayBufferByteLength]] to
slots .
Let obj be ? OrdinaryCreateFromConstructor (constructor ,
"%SharedArrayBuffer.prototype%" , slots ).
If allocatingGrowableBuffer is true , let
allocLength be maxByteLength ; otherwise let
allocLength be byteLength .
Let block be ? CreateSharedByteDataBlock (allocLength ).
Set obj .[[ArrayBufferData]] to block .
If allocatingGrowableBuffer is true , then
Assert : byteLength ≤
maxByteLength .
Let byteLengthBlock be ? CreateSharedByteDataBlock (8).
Perform SetValueInBuffer (byteLengthBlock ,
0, biguint64 , ℤ (byteLength ),
true , seq-cst ).
Set obj .[[ArrayBufferByteLengthData]] to
byteLengthBlock .
Set obj .[[ArrayBufferMaxByteLength]] to
maxByteLength .
Else,
Set obj .[[ArrayBufferByteLength]] to
byteLength .
Return obj .
25.2.2.2 IsSharedArrayBuffer ( obj )
The abstract operation IsSharedArrayBuffer takes argument obj (an ArrayBuffer or a
SharedArrayBuffer) and returns a Boolean. It tests whether an object is an ArrayBuffer, a
SharedArrayBuffer, or a subtype of either. It performs the following steps when called:
Let bufferData be obj .[[ArrayBufferData]] .
If bufferData is null , return
false .
If bufferData is a Data Block , return
false .
Assert :
bufferData is a Shared Data Block .
Return true .
25.2.2.3 HostGrowSharedArrayBuffer ( buffer ,
newByteLength )
The host-defined abstract operation
HostGrowSharedArrayBuffer takes arguments buffer (a SharedArrayBuffer) and
newByteLength (a non-negative integer ) and returns either a normal completion
containing either handled or
unhandled , or a throw completion . It
gives the host an
opportunity to perform implementation-defined growing of
buffer . If the host chooses not to handle growing of buffer ,
it may return unhandled for the default behaviour.
The implementation of HostGrowSharedArrayBuffer must conform to the following requirements:
If the abstract operation does not complete normally with
unhandled , and newByteLength < the current byte
length of the buffer or newByteLength > buffer .[[ArrayBufferMaxByteLength]] , throw a
RangeError exception.
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding
agent 's Agent Record . If the abstract operation
completes normally with handled , a WriteSharedMemory or
ReadModifyWriteSharedMemory
event whose [[Order]] is seq-cst , [[Payload]] is NumericToRawBytes (biguint64 ,
newByteLength , isLittleEndian ), [[Block]]
is buffer .[[ArrayBufferByteLengthData]] , [[ByteIndex]] is 0, and [[ElementSize]]
is 8 is added to the surrounding agent 's candidate execution such that
racing calls to SharedArrayBuffer.prototype.grow are not "lost", i.e.
silently do nothing.
Note
The second requirement above is intentionally vague about how or when the current
byte length of buffer is read. Because the byte length must be updated
via an atomic read-modify-write operation on the underlying hardware, architectures
that use load-link/store-conditional or load-exclusive/store-exclusive instruction
pairs may wish to keep the paired instructions close in the instruction stream. As
such, SharedArrayBuffer.prototype.grow itself does not perform bounds checking on
newByteLength before calling HostGrowSharedArrayBuffer, nor is there a
requirement on when the current byte length is read.
This is in contrast with HostResizeArrayBuffer ,
which is guaranteed that the value of newByteLength is ≥ 0 and ≤
buffer .[[ArrayBufferMaxByteLength]] .
The default implementation of HostGrowSharedArrayBuffer is to return NormalCompletion (unhandled ).
25.2.3 The SharedArrayBuffer Constructor
The SharedArrayBuffer constructor :
is %SharedArrayBuffer% .
is the initial value of the "SharedArrayBuffer" property of the global
object , if that property is present (see below).
creates and initializes a new SharedArrayBuffer when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
SharedArrayBuffer behaviour must include a super call to the SharedArrayBuffer
constructor to create and initialize subclass
instances with the internal state necessary to support the
SharedArrayBuffer.prototype built-in methods.
Whenever a host does not
provide concurrent access to SharedArrayBuffers it may omit the
"SharedArrayBuffer" property of the global object .
Note
Unlike an ArrayBuffer, a SharedArrayBuffer cannot become
detached, and its internal [[ArrayBufferData]] slot is never
null .
25.2.3.1 SharedArrayBuffer ( length [ ,
options ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Let byteLength be ? ToIndex (length ).
Let requestedMaxByteLength be ? GetArrayBufferMaxByteLengthOption (options ).
Return ? AllocateSharedArrayBuffer (NewTarget,
byteLength , requestedMaxByteLength ).
25.2.4 Properties of the SharedArrayBuffer Constructor
The SharedArrayBuffer constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
25.2.4.1 SharedArrayBuffer.prototype
The initial value of SharedArrayBuffer.prototype is the SharedArrayBuffer
prototype object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
25.2.4.2 get SharedArrayBuffer [ %Symbol.species% ]
SharedArrayBuffer[%Symbol.species%] is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
25.2.5 Properties of the SharedArrayBuffer Prototype Object
The SharedArrayBuffer prototype object :
is %SharedArrayBuffer.prototype% .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is an ordinary
object .
does not have an [[ArrayBufferData]] or [[ArrayBufferByteLength]] internal slot.
25.2.5.1 get SharedArrayBuffer.prototype.byteLength
SharedArrayBuffer.prototype.byteLength is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is false , throw a TypeError exception.
Let length be ArrayBufferByteLength (O ,
seq-cst ).
Return 𝔽 (length ).
25.2.5.2 SharedArrayBuffer.prototype.constructor
The initial value of SharedArrayBuffer.prototype.constructor is %SharedArrayBuffer% .
25.2.5.3 SharedArrayBuffer.prototype.grow ( newLength
)
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferMaxByteLength]] ).
If IsSharedArrayBuffer (O )
is false , throw a TypeError exception.
Let newByteLength be ? ToIndex (newLength ).
Let hostHandled be ? HostGrowSharedArrayBuffer (O ,
newByteLength ).
If hostHandled is handled , return
undefined .
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Let byteLengthBlock be O .[[ArrayBufferByteLengthData]] .
Let currentByteLengthRawBytes be GetRawBytesFromSharedBlock (byteLengthBlock ,
0, biguint64 , true ,
seq-cst ).
Let newByteLengthRawBytes be NumericToRawBytes (biguint64 ,
ℤ (newByteLength ),
isLittleEndian ).
Repeat,
NOTE: This is a compare-and-exchange loop to ensure that parallel, racing
grows of the same buffer are totally ordered, are not lost, and do not
silently do nothing. The loop exits if it was able to attempt to grow
uncontended.
Let currentByteLength be ℝ (RawBytesToNumeric (biguint64 ,
currentByteLengthRawBytes , isLittleEndian )).
If newByteLength = currentByteLength , return
undefined .
If newByteLength < currentByteLength or
newByteLength > O .[[ArrayBufferMaxByteLength]] , throw a
RangeError exception.
Let byteLengthDelta be newByteLength -
currentByteLength .
If it is impossible to create a new Shared Data
Block value consisting of byteLengthDelta
bytes, throw a RangeError exception.
NOTE: No new Shared Data Block is
constructed and used here. The observable behaviour of growable
SharedArrayBuffers is specified by allocating a max -sized Shared Data Block at
construction time, and this step captures the requirement that
implementations that run out of memory must throw a
RangeError .
Let readByteLengthRawBytes be AtomicCompareExchangeInSharedBlock (byteLengthBlock ,
0, 8, currentByteLengthRawBytes ,
newByteLengthRawBytes ).
If ByteListEqual (readByteLengthRawBytes ,
currentByteLengthRawBytes ) is true , return
undefined .
Set currentByteLengthRawBytes to
readByteLengthRawBytes .
Note
Spurious failures of the compare-exchange to update the length are prohibited. If the
bounds checking for the new length passes and the implementation is not out of
memory, a ReadModifyWriteSharedMemory
event (i.e. a successful compare-exchange) is always added into the candidate execution .
Parallel calls to SharedArrayBuffer.prototype.grow are totally ordered. For example,
consider two racing calls: sab.grow(10) and sab.grow(20).
One of the two calls is guaranteed to win the race. The call to
sab.grow(10) will never shrink sab even if
sab.grow(20) happened first; in that case it will instead throw a
RangeError.
25.2.5.4 get SharedArrayBuffer.prototype.growable
SharedArrayBuffer.prototype.growable is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is false , throw a TypeError exception.
If IsFixedLengthArrayBuffer (O )
is false , return true ; otherwise return
false .
25.2.5.5 get SharedArrayBuffer.prototype.maxByteLength
SharedArrayBuffer.prototype.maxByteLength is an accessor
property whose set accessor function is undefined .
Its get accessor function performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is false , throw a TypeError exception.
If IsFixedLengthArrayBuffer (O )
is true , then
Let length be O .[[ArrayBufferByteLength]] .
Else,
Let length be O .[[ArrayBufferMaxByteLength]] .
Return 𝔽 (length ).
25.2.5.6 SharedArrayBuffer.prototype.slice ( start ,
end )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (O )
is false , throw a TypeError exception.
Let len be ArrayBufferByteLength (O ,
seq-cst ).
Let relativeStart be ? ToIntegerOrInfinity (start ).
If relativeStart = -∞, let first be 0.
Else if relativeStart < 0, let first be max (len
+ relativeStart , 0).
Else, let first be min (relativeStart ,
len ).
If end is undefined , let relativeEnd be
len ; else let relativeEnd be ? ToIntegerOrInfinity (end ).
If relativeEnd = -∞, let final be 0.
Else if relativeEnd < 0, let final be max (len +
relativeEnd , 0).
Else, let final be min (relativeEnd , len ).
Let newLen be max (final - first , 0).
Let ctor be ? SpeciesConstructor (O ,
%SharedArrayBuffer% ).
Let new be ? Construct (ctor , « 𝔽 (newLen ) »).
Perform ? RequireInternalSlot (new ,
[[ArrayBufferData]] ).
If IsSharedArrayBuffer (new )
is false , throw a TypeError exception.
If new .[[ArrayBufferData]] is O .[[ArrayBufferData]] , throw a TypeError
exception.
If ArrayBufferByteLength (new ,
seq-cst ) < newLen , throw a
TypeError exception.
Let fromBuf be O .[[ArrayBufferData]] .
Let toBuf be new .[[ArrayBufferData]] .
Perform CopyDataBlockBytes (toBuf ,
0, fromBuf , first , newLen ).
Return new .
25.2.5.7 SharedArrayBuffer.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "SharedArrayBuffer" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
25.2.6 Properties of SharedArrayBuffer Instances
SharedArrayBuffer instances inherit properties from the SharedArrayBuffer
prototype object . SharedArrayBuffer instances each have an [[ArrayBufferData]] internal slot. SharedArrayBuffer instances which are
not growable each have an [[ArrayBufferByteLength]] internal slot.
SharedArrayBuffer instances which are growable each have an [[ArrayBufferByteLengthData]] internal slot and an [[ArrayBufferMaxByteLength]] internal slot.
Note
SharedArrayBuffer instances, unlike ArrayBuffer instances, are never detached.
25.2.7 Growable SharedArrayBuffer Guidelines
Note 1
The following are guidelines for ECMAScript programmers working with growable
SharedArrayBuffer .
We recommend that programs be tested in their deployment environments where possible. The
amount of available physical memory differ greatly between hardware devices. Similarly,
virtual memory subsystems also differ greatly between hardware devices as well as
operating systems. An application that runs without out-of-memory errors on a 64-bit
desktop web browser could run out of memory on a 32-bit mobile web browser.
When choosing a value for the "maxByteLength" option for growable
SharedArrayBuffer , we recommend that the smallest possible size
for the application be chosen. We recommend that "maxByteLength" does
not exceed 1073741824, or 1GiB.
Please note that successfully constructing a growable
SharedArrayBuffer for a particular maximum size does not
guarantee that future grows will succeed.
Not all loads of a growable
SharedArrayBuffer 's length are synchronizing
seq-cst loads. Loads of the length that are for bounds-checking
of an integer-indexed property access, e.g.
u8[idx], are not synchronizing. In general, in the absence of explicit
synchronization, one property access being in-bound does not imply a subsequent property
access in the same agent is also in-bound. In contrast, explicit loads
of the length via the length and byteLength getters on
SharedArrayBuffer, %TypedArray% .prototype,
and DataView.prototype are synchronizing. Loads of the length that are performed by
built-in methods to check if a TypedArray is entirely out-of-bounds are also
synchronizing.
Note 2
The following are guidelines for ECMAScript implementers implementing growable
SharedArrayBuffer .
We recommend growable
SharedArrayBuffer be implemented as in-place growth via reserving
virtual memory up front.
Because grow operations can happen in parallel with memory accesses on a growable
SharedArrayBuffer , the constraints of the memory
model require that even unordered accesses do not "tear" (bits of
their values will not be mixed). In practice, this means the underlying data block of a
growable
SharedArrayBuffer cannot be grown by being copied without
stopping the world. We do not recommend stopping the world as an implementation strategy
because it introduces a serialization point and is slow.
Grown memory must appear zeroed from the moment of its creation, including to any racy
accesses in parallel. This can be accomplished via zero-filled-on-demand virtual memory
pages, or careful synchronization if manually zeroing memory.
Integer-indexed property access on
TypedArray views of growable
SharedArrayBuffers is intended to be optimizable similarly to access on TypedArray
views of non-growable SharedArrayBuffers, because integer-indexed property
loads on are not synchronizing on the underlying buffer's length (see programmer
guidelines above). For example, bounds checks for property accesses may still be hoisted
out of loops.
In practice it is difficult to implement growable
SharedArrayBuffer by copying on hosts that do not have virtual
memory, such as those running on embedded devices without an MMU. Memory usage behaviour
of growable SharedArrayBuffers on such hosts may significantly differ from that of
hosts with virtual
memory. Such hosts
should clearly communicate memory usage expectations to users.
25.3 DataView Objects
25.3.1 Abstract Operations For DataView Objects
25.3.1.1 DataView With Buffer Witness Records
A DataView With Buffer
Witness Record is a Record
value used to encapsulate a DataView along with a cached byte length of the viewed buffer.
It is used to help ensure there is a single shared memory read event of the byte length data
block when the viewed buffer is a growable SharedArrayBuffers.
DataView With Buffer Witness Records have the fields listed in Table 77 .
Table 77: DataView
With Buffer Witness Record Fields
Field Name
Value
Meaning
[[Object]]
a DataView
The DataView object whose buffer's byte length is loaded.
[[CachedBufferByteLength]]
a non-negative integer or
detached
The byte length of the object's [[ViewedArrayBuffer]] when the Record
was created.
25.3.1.2 MakeDataViewWithBufferWitnessRecord ( obj ,
order )
The abstract operation MakeDataViewWithBufferWitnessRecord takes arguments obj (a
DataView) and order (seq-cst or
unordered ) and returns a DataView With Buffer Witness
Record . It performs the following steps when called:
Let buffer be obj .[[ViewedArrayBuffer]] .
If IsDetachedBuffer (buffer )
is true , then
Let byteLength be detached .
Else,
Let byteLength be ArrayBufferByteLength (buffer ,
order ).
Return the DataView
With Buffer Witness Record { [[Object]] : obj , [[CachedBufferByteLength]] : byteLength }.
25.3.1.3 GetViewByteLength ( viewRecord )
The abstract operation GetViewByteLength takes argument viewRecord (a DataView With Buffer Witness
Record ) and returns a non-negative integer . It performs the following
steps when called:
Assert :
IsViewOutOfBounds (viewRecord )
is false .
Let view be viewRecord .[[Object]] .
If view .[[ByteLength]] is not
auto , return view .[[ByteLength]] .
Assert :
IsFixedLengthArrayBuffer (view .[[ViewedArrayBuffer]] ) is false .
Let byteOffset be view .[[ByteOffset]] .
Let byteLength be viewRecord .[[CachedBufferByteLength]] .
Assert :
byteLength is not detached .
Return byteLength - byteOffset .
25.3.1.4 IsViewOutOfBounds ( viewRecord )
The abstract operation IsViewOutOfBounds takes argument viewRecord (a DataView With Buffer Witness
Record ) and returns a Boolean. It performs the following steps when
called:
Let view be viewRecord .[[Object]] .
Let bufferByteLength be viewRecord .[[CachedBufferByteLength]] .
Assert :
IsDetachedBuffer (view .[[ViewedArrayBuffer]] ) is true if and
only if bufferByteLength is detached .
If bufferByteLength is detached , return
true .
Let byteOffsetStart be view .[[ByteOffset]] .
If view .[[ByteLength]] is
auto , then
Let byteOffsetEnd be bufferByteLength .
Else,
Let byteOffsetEnd be byteOffsetStart +
view .[[ByteLength]] .
If byteOffsetStart > bufferByteLength or
byteOffsetEnd > bufferByteLength , return
true .
NOTE: 0-length DataViews are not considered out-of-bounds.
Return false .
25.3.1.5 GetViewValue ( view ,
requestIndex , isLittleEndian , type )
The abstract operation GetViewValue takes arguments view (an ECMAScript language value ),
requestIndex (an ECMAScript language
value ), isLittleEndian (an ECMAScript language value ), and
type (a TypedArray element type ) and returns
either a normal completion
containing either a Number or a BigInt, or a throw completion . It
is used by functions on DataView instances to retrieve values from the view's buffer. It
performs the following steps when called:
Perform ? RequireInternalSlot (view ,
[[DataView]] ).
Assert :
view has a [[ViewedArrayBuffer]] internal slot.
Let getIndex be ? ToIndex (requestIndex ).
Set isLittleEndian to ToBoolean (isLittleEndian ).
Let viewOffset be view .[[ByteOffset]] .
Let viewRecord be MakeDataViewWithBufferWitnessRecord (view ,
unordered ).
NOTE: Bounds checking is not a synchronizing operation when view 's
backing buffer is a growable
SharedArrayBuffer .
If IsViewOutOfBounds (viewRecord )
is true , throw a TypeError exception.
Let viewSize be GetViewByteLength (viewRecord ).
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
If getIndex + elementSize > viewSize , throw a
RangeError exception.
Let bufferIndex be getIndex + viewOffset .
Return GetValueFromBuffer (view .[[ViewedArrayBuffer]] , bufferIndex ,
type , false , unordered ,
isLittleEndian ).
25.3.1.6 SetViewValue ( view ,
requestIndex , isLittleEndian , type , value )
The abstract operation SetViewValue takes arguments view (an ECMAScript language value ),
requestIndex (an ECMAScript language
value ), isLittleEndian (an ECMAScript language value ),
type (a TypedArray element type ), and
value (an ECMAScript language value ) and
returns either a normal completion
containing undefined or a throw completion . It
is used by functions on DataView instances to store values into the view's buffer. It
performs the following steps when called:
Perform ? RequireInternalSlot (view ,
[[DataView]] ).
Assert :
view has a [[ViewedArrayBuffer]] internal slot.
Let getIndex be ? ToIndex (requestIndex ).
If IsBigIntElementType (type )
is true , let numberValue be ? ToBigInt (value ).
Otherwise, let numberValue be ? ToNumber (value ).
Set isLittleEndian to ToBoolean (isLittleEndian ).
Let viewOffset be view .[[ByteOffset]] .
Let viewRecord be MakeDataViewWithBufferWitnessRecord (view ,
unordered ).
NOTE: Bounds checking is not a synchronizing operation when view 's
backing buffer is a growable
SharedArrayBuffer .
If IsViewOutOfBounds (viewRecord )
is true , throw a TypeError exception.
Let viewSize be GetViewByteLength (viewRecord ).
Let elementSize be the Element Size value specified in Table 75 for
Element Type type .
If getIndex + elementSize > viewSize , throw a
RangeError exception.
Let bufferIndex be getIndex + viewOffset .
Perform SetValueInBuffer (view .[[ViewedArrayBuffer]] , bufferIndex ,
type , numberValue , false ,
unordered , isLittleEndian ).
Return undefined .
25.3.2 The DataView Constructor
The DataView constructor :
is %DataView% .
is the initial value of the "DataView" property of the global
object .
creates and initializes a new DataView when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
DataView behaviour must include a super call to the DataView constructor to
create and initialize subclass instances with the internal state necessary to support the
DataView.prototype built-in methods.
25.3.2.1 DataView ( buffer [ , byteOffset
[ , byteLength ] ] )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Perform ? RequireInternalSlot (buffer ,
[[ArrayBufferData]] ).
Let offset be ? ToIndex (byteOffset ).
If IsDetachedBuffer (buffer )
is true , throw a TypeError exception.
Let bufferByteLength be ArrayBufferByteLength (buffer ,
seq-cst ).
If offset > bufferByteLength , throw a
RangeError exception.
Let bufferIsFixedLength be IsFixedLengthArrayBuffer (buffer ).
If byteLength is undefined , then
If bufferIsFixedLength is true , then
Let viewByteLength be bufferByteLength -
offset .
Else,
Let viewByteLength be auto .
Else,
Let viewByteLength be ? ToIndex (byteLength ).
If offset + viewByteLength >
bufferByteLength , throw a RangeError
exception.
Let O be ? OrdinaryCreateFromConstructor (NewTarget,
"%DataView.prototype%" , « [[DataView]] ,
[[ViewedArrayBuffer]] , [[ByteLength]] , [[ByteOffset]] »).
If IsDetachedBuffer (buffer )
is true , throw a TypeError exception.
Set bufferByteLength to ArrayBufferByteLength (buffer ,
seq-cst ).
If offset > bufferByteLength , throw a
RangeError exception.
If byteLength is not undefined , then
If offset + viewByteLength >
bufferByteLength , throw a RangeError
exception.
Set O .[[ViewedArrayBuffer]] to
buffer .
Set O .[[ByteLength]] to
viewByteLength .
Set O .[[ByteOffset]] to offset .
Return O .
25.3.3 Properties of the DataView Constructor
The DataView constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
25.3.3.1 DataView.prototype
The initial value of DataView.prototype is the DataView prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
25.3.4 Properties of the DataView Prototype Object
The DataView prototype object :
is %DataView.prototype% .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is an ordinary
object .
does not have a [[DataView]] , [[ViewedArrayBuffer]] , [[ByteLength]] , or
[[ByteOffset]] internal slot.
25.3.4.1 get DataView.prototype.buffer
DataView.prototype.buffer is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[DataView]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let buffer be O .[[ViewedArrayBuffer]] .
Return buffer .
25.3.4.2 get DataView.prototype.byteLength
DataView.prototype.byteLength is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[DataView]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let viewRecord be MakeDataViewWithBufferWitnessRecord (O ,
seq-cst ).
If IsViewOutOfBounds (viewRecord )
is true , throw a TypeError exception.
Let size be GetViewByteLength (viewRecord ).
Return 𝔽 (size ).
25.3.4.3 get DataView.prototype.byteOffset
DataView.prototype.byteOffset is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[DataView]] ).
Assert :
O has a [[ViewedArrayBuffer]] internal slot.
Let viewRecord be MakeDataViewWithBufferWitnessRecord (O ,
seq-cst ).
If IsViewOutOfBounds (viewRecord )
is true , throw a TypeError exception.
Let offset be O .[[ByteOffset]] .
Return 𝔽 (offset ).
25.3.4.4 DataView.prototype.constructor
The initial value of DataView.prototype.constructor is %DataView% .
25.3.4.5 DataView.prototype.getBigInt64 ( byteOffset
[ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
Return ? GetViewValue (view ,
byteOffset , littleEndian , bigint64 ).
25.3.4.6 DataView.prototype.getBigUint64 ( byteOffset
[ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
Return ? GetViewValue (view ,
byteOffset , littleEndian , biguint64 ).
25.3.4.7 DataView.prototype.getFloat16 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , float16 ).
25.3.4.8 DataView.prototype.getFloat32 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , float32 ).
25.3.4.9 DataView.prototype.getFloat64 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , float64 ).
25.3.4.10 DataView.prototype.getInt8 ( byteOffset )
This method performs the following steps when called:
Let view be the this value.
Return ? GetViewValue (view ,
byteOffset , true , int8 ).
25.3.4.11 DataView.prototype.getInt16 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , int16 ).
25.3.4.12 DataView.prototype.getInt32 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , int32 ).
25.3.4.13 DataView.prototype.getUint8 ( byteOffset )
This method performs the following steps when called:
Let view be the this value.
Return ? GetViewValue (view ,
byteOffset , true , uint8 ).
25.3.4.14 DataView.prototype.getUint16 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , uint16 ).
25.3.4.15 DataView.prototype.getUint32 ( byteOffset [
, littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? GetViewValue (view ,
byteOffset , littleEndian , uint32 ).
25.3.4.16 DataView.prototype.setBigInt64 (
byteOffset , value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
Return ? SetViewValue (view ,
byteOffset , littleEndian , bigint64 ,
value ).
25.3.4.17 DataView.prototype.setBigUint64 (
byteOffset , value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
Return ? SetViewValue (view ,
byteOffset , littleEndian , biguint64 ,
value ).
25.3.4.18 DataView.prototype.setFloat16 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , float16 ,
value ).
25.3.4.19 DataView.prototype.setFloat32 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , float32 ,
value ).
25.3.4.20 DataView.prototype.setFloat64 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , float64 ,
value ).
25.3.4.21 DataView.prototype.setInt8 ( byteOffset ,
value )
This method performs the following steps when called:
Let view be the this value.
Return ? SetViewValue (view ,
byteOffset , true , int8 ,
value ).
25.3.4.22 DataView.prototype.setInt16 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , int16 ,
value ).
25.3.4.23 DataView.prototype.setInt32 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , int32 ,
value ).
25.3.4.24 DataView.prototype.setUint8 ( byteOffset ,
value )
This method performs the following steps when called:
Let view be the this value.
Return ? SetViewValue (view ,
byteOffset , true , uint8 ,
value ).
25.3.4.25 DataView.prototype.setUint16 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , uint16 ,
value ).
25.3.4.26 DataView.prototype.setUint32 ( byteOffset ,
value [ , littleEndian ] )
This method performs the following steps when called:
Let view be the this value.
If littleEndian is not present, set littleEndian to
false .
Return ? SetViewValue (view ,
byteOffset , littleEndian , uint32 ,
value ).
25.3.4.27 DataView.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "DataView" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
25.3.5 Properties of DataView Instances
DataView instances are ordinary objects that inherit properties from the
DataView prototype
object . DataView instances each have [[DataView]] , [[ViewedArrayBuffer]] , [[ByteLength]] , and [[ByteOffset]] internal
slots.
Note
The value of the [[DataView]] internal slot is not used within
this specification. The simple presence of that internal slot is used within the
specification to identify objects created using the DataView constructor .
25.4 The Atomics Object
The Atomics object:
is %Atomics% .
is the initial value of the "Atomics" property of the global
object .
is an ordinary
object .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
does not have a [[Construct]] internal method; it cannot be used as a
constructor
with the new operator.
does not have a [[Call]] internal method; it cannot be invoked as a
function.
The Atomics object provides functions that operate indivisibly (atomically) on shared memory array
cells as well as functions that let agents wait for and dispatch primitive events. When used with
discipline, the Atomics functions allow multi-agent programs that communicate through shared memory to
execute in a well-understood order even on parallel CPUs. The rules that govern shared-memory
communication are provided by the memory model , defined below.
Note
For informative guidelines for programming and implementing shared memory in ECMAScript,
please see the notes at the end of the memory model section.
25.4.1 Waiter Record
A Waiter Record is a Record value used to
denote a particular call to Atomics.wait or Atomics.waitAsync.
A Waiter Record has fields listed in Table 78 .
Table 78: Waiter Record Fields
Field Name
Value
Meaning
[[AgentSignifier]]
an agent
signifier
The agent that called
Atomics.wait or Atomics.waitAsync.
[[PromiseCapability]]
a PromiseCapability
Record or blocking
If denoting a call to Atomics.waitAsync, the resulting promise,
otherwise blocking .
[[TimeoutTime]]
a non-negative extended
mathematical value
The earliest time by which timeout may be triggered; computed using
time values .
[[Result]]
"ok" or "timed-out"
The return value of the call.
25.4.2 WaiterList Records
A WaiterList Record is used to explain
waiting and notification of agents via Atomics.wait,
Atomics.waitAsync, and Atomics.notify.
A WaiterList Record has fields listed in Table 79 .
Table 79: WaiterList Record Fields
Field Name
Value
Meaning
[[Waiters]]
a List
of Waiter Records
The calls to Atomics.wait or Atomics.waitAsync
that are waiting on the location with which this WaiterList is associated.
[[MostRecentLeaveEvent]]
a Synchronize
event or empty
The event of the most recent leaving of its critical section , or
empty if its critical
section has never been entered.
There can be multiple Waiter Records in a WaiterList with the same
agent
signifier .
The agent
cluster has a store of WaiterList Records; the store is indexed by
(block , i ), where block is a Shared Data Block and i
a byte offset into the memory of block . WaiterList Records are agent -independent: a lookup in
the store of WaiterList Records by (block , i ) will result in the same
WaiterList Record in any agent in the agent cluster .
Each WaiterList Record has a critical
section that controls exclusive access to that WaiterList Record during evaluation.
Only a single agent may
enter a WaiterList Record's critical section at one time. Entering and leaving a WaiterList
Record's critical section is controlled by the abstract operations
EnterCriticalSection and LeaveCriticalSection . Operations on a
WaiterList Record—adding and removing waiting agents , traversing the list of agents , suspending and notifying agents on the list, setting
and retrieving the Synchronize event —may only be
performed by agents that
have entered the WaiterList Record's critical section.
25.4.3 Abstract Operations for Atomics
25.4.3.1 ValidateIntegerTypedArray ( typedArray ,
waitable )
The abstract operation ValidateIntegerTypedArray takes arguments typedArray (an
ECMAScript language value ) and
waitable (a Boolean) and returns either a normal completion
containing a TypedArray With Buffer Witness
Record , or a throw completion . It
performs the following steps when called:
Let taRecord be ? ValidateTypedArray (typedArray ,
unordered ).
NOTE: Bounds checking is not a synchronizing operation when typedArray 's
backing buffer is a growable
SharedArrayBuffer .
If waitable is true , then
If typedArray .[[TypedArrayName]] is
neither "Int32Array" nor
"BigInt64Array" , throw a TypeError
exception.
Else,
Let type be TypedArrayElementType (typedArray ).
If IsUnclampedIntegerElementType (type )
is false and IsBigIntElementType (type )
is false , throw a TypeError exception.
Return taRecord .
25.4.3.2 ValidateAtomicAccess ( taRecord ,
requestIndex )
The abstract operation ValidateAtomicAccess takes arguments taRecord (a TypedArray With Buffer Witness
Record ) and requestIndex (an ECMAScript language value ) and
returns either a normal completion
containing an integer or a throw completion . It
performs the following steps when called:
Let length be TypedArrayLength (taRecord ).
Let accessIndex be ? ToIndex (requestIndex ).
Assert :
accessIndex ≥ 0.
If accessIndex ≥ length , throw a RangeError
exception.
Let typedArray be taRecord .[[Object]] .
Let elementSize be TypedArrayElementSize (typedArray ).
Let offset be typedArray .[[ByteOffset]] .
Return (accessIndex × elementSize ) + offset .
25.4.3.3 ValidateAtomicAccessOnIntegerTypedArray (
typedArray , requestIndex )
The abstract operation ValidateAtomicAccessOnIntegerTypedArray takes arguments
typedArray (an ECMAScript language value ) and
requestIndex (an ECMAScript language
value ) and returns either a normal completion
containing an integer or a throw completion . It
performs the following steps when called:
Let taRecord be ? ValidateIntegerTypedArray (typedArray ,
false ).
Return ? ValidateAtomicAccess (taRecord ,
requestIndex ).
25.4.3.4 RevalidateAtomicAccess ( typedArray ,
byteIndexInBuffer )
The abstract operation RevalidateAtomicAccess takes arguments typedArray (a
TypedArray ) and byteIndexInBuffer (an
integer ) and
returns either a normal completion
containing unused or a throw completion .
This operation revalidates the index within the backing buffer for atomic operations after
all argument coercions are performed in Atomics methods, as argument coercions can have
arbitrary side effects, which could cause the buffer to become out of bounds. This operation
does not throw when typedArray 's backing buffer is a SharedArrayBuffer. It
performs the following steps when called:
Let taRecord be MakeTypedArrayWithBufferWitnessRecord (typedArray ,
unordered ).
NOTE: Bounds checking is not a synchronizing operation when typedArray 's
backing buffer is a growable
SharedArrayBuffer .
If IsTypedArrayOutOfBounds (taRecord )
is true , throw a TypeError exception.
Assert :
byteIndexInBuffer ≥ typedArray .[[ByteOffset]] .
If byteIndexInBuffer ≥ taRecord .[[CachedBufferByteLength]] , throw a
RangeError exception.
Return unused .
25.4.3.5 GetWaiterList ( block , i )
The abstract operation GetWaiterList takes arguments block (a Shared Data
Block ) and i (a non-negative integer that is evenly divisible by 4)
and returns a WaiterList Record . It performs the
following steps when called:
Assert :
i and i + 3 are valid byte offsets within the memory of
block .
Return the WaiterList Record that is
referenced by the pair (block , i ).
25.4.3.6 EnterCriticalSection ( WL )
The abstract operation EnterCriticalSection takes argument WL (a WaiterList Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is not in the
critical section for any
WaiterList Record .
Wait until no agent is in the critical section for
WL , then enter the critical
section for WL (without allowing any other
agent to
enter).
If WL .[[MostRecentLeaveEvent]] is not
empty , then
NOTE: A WL whose critical
section has been entered at least once has a
Synchronize
event set by LeaveCriticalSection .
Let execution be the [[CandidateExecution]] field of the surrounding agent 's
Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
Let enterEvent be a new Synchronize
event .
Append enterEvent to eventsRecord .[[EventList]] .
Append (WL .[[MostRecentLeaveEvent]] ,
enterEvent ) to eventsRecord .[[AgentSynchronizesWith]] .
Return unused .
EnterCriticalSection has contention when an agent attempting to enter the critical section must wait for another
agent to leave it.
When there is no contention, FIFO order of EnterCriticalSection calls is observable. When
there is contention, an implementation may choose an arbitrary order but may not cause an
agent to wait
indefinitely.
25.4.3.7 LeaveCriticalSection ( WL )
The abstract operation LeaveCriticalSection takes argument WL (a WaiterList Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
Let execution be the [[CandidateExecution]]
field of the surrounding agent 's Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
Let leaveEvent be a new Synchronize
event .
Append leaveEvent to eventsRecord .[[EventList]] .
Set WL .[[MostRecentLeaveEvent]] to
leaveEvent .
Leave the critical section for
WL .
Return unused .
25.4.3.8 AddWaiter ( WL , waiterRecord )
The abstract operation AddWaiter takes arguments WL (a WaiterList Record ) and
waiterRecord (a Waiter Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
Assert :
There is no Waiter Record in WL .[[Waiters]] whose [[PromiseCapability]] field is waiterRecord .[[PromiseCapability]] and whose [[AgentSignifier]] field is waiterRecord .[[AgentSignifier]] .
Append waiterRecord to WL .[[Waiters]] .
Return unused .
25.4.3.9 RemoveWaiter ( WL , waiterRecord )
The abstract operation RemoveWaiter takes arguments WL (a WaiterList Record ) and
waiterRecord (a Waiter Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
Assert :
WL .[[Waiters]] contains waiterRecord .
Remove waiterRecord from WL .[[Waiters]] .
Return unused .
25.4.3.10 RemoveWaiters ( WL , c )
The abstract operation RemoveWaiters takes arguments WL (a WaiterList Record ) and c (a
non-negative integer or +∞) and returns a List of Waiter
Records . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
Let len be the number of elements in WL .[[Waiters]] .
Let n be min (c , len ).
Let L be a List whose
elements are the first n elements of WL .[[Waiters]] .
Remove the first n elements of WL .[[Waiters]] .
Return L .
25.4.3.11 SuspendThisAgent ( WL ,
waiterRecord )
The abstract operation SuspendThisAgent takes arguments WL (a WaiterList Record ) and
waiterRecord (a Waiter Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
Assert :
WL .[[Waiters]] contains waiterRecord .
Let thisAgent be AgentSignifier ().
Assert :
waiterRecord .[[AgentSignifier]] is
thisAgent .
Assert :
waiterRecord .[[PromiseCapability]] is
blocking .
Assert :
AgentCanSuspend () is
true .
Perform LeaveCriticalSection (WL )
and suspend the surrounding agent until the time is
waiterRecord .[[TimeoutTime]] , performing the
combined operation in such a way that a notification that arrives after the
critical section is exited but
before the suspension takes effect is not lost. The surrounding agent can only wake
from suspension due to a timeout or due to another agent calling NotifyWaiter with arguments
WL and thisAgent (i.e. via a call to
Atomics.notify).
Perform EnterCriticalSection (WL ).
Return unused .
25.4.3.12 NotifyWaiter ( WL , waiterRecord
)
The abstract operation NotifyWaiter takes arguments WL (a WaiterList Record ) and
waiterRecord (a Waiter Record ) and returns
unused . It performs the following steps when called:
Assert :
The surrounding agent is in the
critical section for
WL .
If waiterRecord .[[PromiseCapability]] is
blocking , then
Wake the agent whose signifier is
waiterRecord .[[AgentSignifier]] from
suspension.
NOTE: This causes the agent to resume execution in SuspendThisAgent .
Else if AgentSignifier () is
waiterRecord .[[AgentSignifier]] , then
Let promiseCapability be waiterRecord .[[PromiseCapability]] .
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
waiterRecord .[[Result]] »).
Else,
Perform EnqueueResolveInAgentJob (waiterRecord .[[AgentSignifier]] , waiterRecord .[[PromiseCapability]] , waiterRecord .[[Result]] ).
Return unused .
Note
An agent must
not access another agent 's promise capability in any capacity
beyond passing it to the host .
25.4.3.13 EnqueueResolveInAgentJob ( agentSignifier ,
promiseCapability , resolution )
The abstract operation EnqueueResolveInAgentJob takes arguments agentSignifier (an
agent
signifier ), promiseCapability (a PromiseCapability Record ), and
resolution ("ok" or "timed-out" ) and
returns unused . It performs the following steps when called:
Let resolveJob be a new Job Abstract Closure
with no parameters that captures agentSignifier ,
promiseCapability , and resolution and performs the following
steps when called:
Assert : AgentSignifier () is
agentSignifier .
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
resolution »).
Return unused .
Let realmInTargetAgent be ! GetFunctionRealm (promiseCapability .[[Resolve]] ).
Assert :
agentSignifier is realmInTargetAgent .[[AgentSignifier]] .
Perform HostEnqueueGenericJob (resolveJob ,
realmInTargetAgent ).
Return unused .
25.4.3.14 DoWait ( mode , typedArray ,
index , value , timeout )
The abstract operation DoWait takes arguments mode (sync or
async ), typedArray (an ECMAScript language value ),
index (an ECMAScript language value ),
value (an ECMAScript language value ), and
timeout (an ECMAScript language value ) and
returns either a normal completion
containing either an Object, "not-equal" ,
"timed-out" , or "ok" , or a throw completion . It
performs the following steps when called:
Let taRecord be ? ValidateIntegerTypedArray (typedArray ,
true ).
Let buffer be taRecord .[[Object]] .[[ViewedArrayBuffer]] .
If IsSharedArrayBuffer (buffer )
is false , throw a TypeError exception.
Let i be ? ValidateAtomicAccess (taRecord ,
index ).
Let arrayTypeName be typedArray .[[TypedArrayName]] .
If arrayTypeName is "BigInt64Array" , let v
be ? ToBigInt64 (value ).
Else, let v be ? ToInt32 (value ).
Let q be ? ToNumber (timeout ).
If q is either NaN or
+∞ 𝔽 , let t be +∞; else if q is
-∞ 𝔽 , let t be 0; else let t be
max (ℝ (q ), 0).
If mode is sync and AgentCanSuspend () is
false , throw a TypeError exception.
Let block be buffer .[[ArrayBufferData]] .
Let offset be typedArray .[[ByteOffset]] .
Let byteIndexInBuffer be (i × 4) + offset .
Let WL be GetWaiterList (block ,
byteIndexInBuffer ).
If mode is sync , then
Let promiseCapability be blocking .
Let resultObject be undefined .
Else,
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let resultObject be OrdinaryObjectCreate (%Object.prototype% ).
Perform EnterCriticalSection (WL ).
Let elementType be TypedArrayElementType (typedArray ).
Let w be GetValueFromBuffer (buffer ,
byteIndexInBuffer , elementType , true ,
seq-cst ).
If v ≠ w , then
Perform LeaveCriticalSection (WL ).
If mode is sync , return
"not-equal" .
Perform ! CreateDataPropertyOrThrow (resultObject ,
"async" , false ).
Perform ! CreateDataPropertyOrThrow (resultObject ,
"value" , "not-equal" ).
Return resultObject .
If t = 0 and mode is async , then
NOTE: There is no special handling of synchronous immediate timeouts.
Asynchronous immediate timeouts have special handling in order to fail fast
and avoid unnecessary Promise jobs.
Perform LeaveCriticalSection (WL ).
Perform ! CreateDataPropertyOrThrow (resultObject ,
"async" , false ).
Perform ! CreateDataPropertyOrThrow (resultObject ,
"value" , "timed-out" ).
Return resultObject .
Let thisAgent be AgentSignifier ().
Let now be the time
value (UTC) identifying the current time.
Let additionalTimeout be an implementation-defined
non-negative mathematical value .
Let timeoutTime be ℝ (now ) + t +
additionalTimeout .
NOTE: When t is +∞, timeoutTime is also +∞.
Let waiterRecord be a new Waiter Record { [[AgentSignifier]] : thisAgent , [[PromiseCapability]] : promiseCapability , [[TimeoutTime]] : timeoutTime , [[Result]] : "ok" }.
Perform AddWaiter (WL ,
waiterRecord ).
If mode is sync , then
Perform SuspendThisAgent (WL ,
waiterRecord ).
Else if timeoutTime is finite , then
Perform EnqueueAtomicsWaitAsyncTimeoutJob (WL ,
waiterRecord ).
Perform LeaveCriticalSection (WL ).
If mode is sync , return
waiterRecord .[[Result]] .
Perform ! CreateDataPropertyOrThrow (resultObject ,
"async" , true ).
Perform ! CreateDataPropertyOrThrow (resultObject ,
"value" , promiseCapability .[[Promise]] ).
Return resultObject .
Note
additionalTimeout allows implementations to pad timeouts as necessary,
such as for reducing power consumption or coarsening timer resolution to mitigate
timing attacks. This value may differ from call to call of DoWait.
25.4.3.15 EnqueueAtomicsWaitAsyncTimeoutJob ( WL ,
waiterRecord )
The abstract operation EnqueueAtomicsWaitAsyncTimeoutJob takes arguments WL (a
WaiterList Record ) and
waiterRecord (a Waiter Record ) and returns
unused . It performs the following steps when called:
Let timeoutJob be a new Job Abstract Closure
with no parameters that captures WL and waiterRecord and
performs the following steps when called:
Perform EnterCriticalSection (WL ).
If WL .[[Waiters]] contains
waiterRecord , then
Let timeOfJobExecution be the time
value (UTC) identifying the current time.
Assert : ℝ (timeOfJobExecution ) ≥
waiterRecord .[[TimeoutTime]]
(ignoring potential non-monotonicity of time
values ).
Set waiterRecord .[[Result]] to
"timed-out" .
Perform RemoveWaiter (WL ,
waiterRecord ).
Perform NotifyWaiter (WL ,
waiterRecord ).
Perform LeaveCriticalSection (WL ).
Return unused .
Let now be the time
value (UTC) identifying the current time.
Let currentRealm be the current Realm Record .
Perform HostEnqueueTimeoutJob (timeoutJob ,
currentRealm , 𝔽 (waiterRecord .[[TimeoutTime]] ) - now ).
Return unused .
25.4.3.16 AtomicCompareExchangeInSharedBlock ( block ,
byteIndexInBuffer , elementSize , expectedBytes ,
replacementBytes )
The abstract operation AtomicCompareExchangeInSharedBlock takes arguments block (a
Shared Data
Block ), byteIndexInBuffer (an integer ), elementSize (a
non-negative integer ), expectedBytes (a List of byte
values ), and replacementBytes (a List of byte
values ) and returns a List of byte
values . It performs the following steps when called:
Let execution be the [[CandidateExecution]]
field of the surrounding agent 's Agent
Record .
Let eventsRecord be the Agent Events
Record of execution .[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier ().
Let rawBytesRead be a List of length
elementSize whose elements are nondeterministically chosen byte
values .
NOTE: In implementations, rawBytesRead is the result of a load-link, of a
load-exclusive, or of an operand of a read-modify-write instruction on the
underlying hardware. The nondeterminism is a semantic prescription of the memory
model to describe observable behaviour of hardware with weak
consistency.
NOTE: The comparison of the expected value and the read value is performed outside
of the read-modify-write modification
function to avoid needlessly strong synchronization when the
expected value is not equal to the read value.
If ByteListEqual (rawBytesRead ,
expectedBytes ) is true , then
Let second be a new read-modify-write
modification function with parameters
(oldBytes , newBytes ) that captures nothing and
performs the following steps atomically when called:
Return newBytes .
Let event be ReadModifyWriteSharedMemory
{ [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndexInBuffer , [[ElementSize]] : elementSize , [[Payload]] : replacementBytes , [[ModifyOp]] : second }.
Else,
Let event be ReadSharedMemory
{ [[Order]] : seq-cst , [[NoTear]] : true , [[Block]] : block , [[ByteIndex]] : byteIndexInBuffer , [[ElementSize]] : elementSize }.
Append event to eventsRecord .[[EventList]] .
Append Chosen Value Record { [[Event]] : event , [[ChosenValue]] : rawBytesRead } to
execution .[[ChosenValues]] .
Return rawBytesRead .
25.4.3.17 AtomicReadModifyWrite ( typedArray ,
index , value , op )
The abstract operation AtomicReadModifyWrite takes arguments typedArray (an
ECMAScript language value ),
index (an ECMAScript language value ),
value (an ECMAScript language value ), and
op (a read-modify-write modification
function ) and returns either a normal completion
containing either a Number or a BigInt, or a throw completion .
op takes two List of
byte
values arguments and returns a List of byte
values . This operation atomically loads a value, combines it with
another value, and stores the combination. It returns the loaded value. It performs the
following steps when called:
Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray (typedArray ,
index ).
If typedArray .[[ContentType]] is
bigint , let v be ? ToBigInt (value ).
Otherwise, let v be 𝔽 (? ToIntegerOrInfinity (value )).
Perform ? RevalidateAtomicAccess (typedArray ,
byteIndexInBuffer ).
Let buffer be typedArray .[[ViewedArrayBuffer]] .
Let elementType be TypedArrayElementType (typedArray ).
Return GetModifySetValueInBuffer (buffer ,
byteIndexInBuffer , elementType , v , op ).
25.4.3.18 ByteListBitwiseOp ( op , xBytes ,
yBytes )
The abstract operation ByteListBitwiseOp takes arguments op (&,
^, or |), xBytes (a List of byte
values ), and yBytes (a List of byte
values ) and returns a List of byte
values . The operation atomically performs a bitwise operation on all
byte
values of the arguments and returns a List of byte
values . It performs the following steps when called:
Assert :
xBytes and yBytes have the same number of elements.
Let result be a new empty List .
Let i be 0.
For each element xByte of xBytes , do
Let yByte be yBytes [i ].
If op is &, then
Let resultByte be the result of applying the bitwise AND
operation to xByte and yByte .
Else if op is ^, then
Let resultByte be the result of applying the bitwise
exclusive OR (XOR) operation to xByte and
yByte .
Else,
Assert : op is
|.
Let resultByte be the result of applying the bitwise
inclusive OR operation to xByte and yByte .
Set i to i + 1.
Append resultByte to result .
Return result .
25.4.3.19 ByteListEqual ( xBytes , yBytes )
The abstract operation ByteListEqual takes arguments xBytes (a List of byte
values ) and yBytes (a List of byte
values ) and returns a Boolean. It performs the following steps when
called:
If xBytes and yBytes do not have the same number of elements,
return false .
Let i be 0.
For each element xByte of xBytes , do
Let yByte be yBytes [i ].
If xByte ≠ yByte , return false .
Set i to i + 1.
Return true .
25.4.4 Atomics.add ( typedArray , index ,
value )
This function performs the following steps when called:
Let add be a new read-modify-write modification
function with parameters (xBytes , yBytes )
that captures typedArray and performs the following steps atomically when
called:
Let type be TypedArrayElementType (typedArray ).
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Let x be RawBytesToNumeric (type ,
xBytes , isLittleEndian ).
Let y be RawBytesToNumeric (type ,
yBytes , isLittleEndian ).
If x is a
Number , then
Let sum be Number::add (x ,
y ).
Else,
Assert : x is a
BigInt .
Let sum be BigInt::add (x ,
y ).
Let sumBytes be NumericToRawBytes (type ,
sum , isLittleEndian ).
Assert : sumBytes ,
xBytes , and yBytes have the same number of elements.
Return sumBytes .
Return ? AtomicReadModifyWrite (typedArray ,
index , value , add ).
25.4.5 Atomics.and ( typedArray , index ,
value )
This function performs the following steps when called:
Let and be a new read-modify-write modification
function with parameters (xBytes , yBytes )
that captures nothing and performs the following steps atomically when called:
Return ByteListBitwiseOp (&,
xBytes , yBytes ).
Return ? AtomicReadModifyWrite (typedArray ,
index , value , and ).
25.4.6 Atomics.compareExchange ( typedArray ,
index , expectedValue , replacementValue )
This function performs the following steps when called:
Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray (typedArray ,
index ).
Let buffer be typedArray .[[ViewedArrayBuffer]] .
Let block be buffer .[[ArrayBufferData]] .
If typedArray .[[ContentType]] is
bigint , then
Let expected be ? ToBigInt (expectedValue ).
Let replacement be ? ToBigInt (replacementValue ).
Else,
Let expected be 𝔽 (? ToIntegerOrInfinity (expectedValue )).
Let replacement be 𝔽 (? ToIntegerOrInfinity (replacementValue )).
Perform ? RevalidateAtomicAccess (typedArray ,
byteIndexInBuffer ).
Let elementType be TypedArrayElementType (typedArray ).
Let elementSize be TypedArrayElementSize (typedArray ).
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding
agent 's Agent Record .
Let expectedBytes be NumericToRawBytes (elementType ,
expected , isLittleEndian ).
Let replacementBytes be NumericToRawBytes (elementType ,
replacement , isLittleEndian ).
If IsSharedArrayBuffer (buffer )
is true , then
Let rawBytesRead be AtomicCompareExchangeInSharedBlock (block ,
byteIndexInBuffer , elementSize , expectedBytes ,
replacementBytes ).
Else,
Let rawBytesRead be a List of
length elementSize whose elements are the sequence of
elementSize bytes starting with
block [byteIndexInBuffer ].
If ByteListEqual (rawBytesRead ,
expectedBytes ) is true , then
Store the individual bytes of replacementBytes into
block , starting at
block [byteIndexInBuffer ].
Return RawBytesToNumeric (elementType ,
rawBytesRead , isLittleEndian ).
25.4.7 Atomics.exchange ( typedArray , index ,
value )
This function performs the following steps when called:
Let second be a new read-modify-write modification
function with parameters (oldBytes ,
newBytes ) that captures nothing and performs the following steps atomically
when called:
Return newBytes .
Return ? AtomicReadModifyWrite (typedArray ,
index , value , second ).
25.4.8 Atomics.isLockFree ( size )
This function performs the following steps when called:
Let n be ? ToIntegerOrInfinity (size ).
Let AR be the Agent Record of the surrounding
agent .
If n = 1, return AR .[[IsLockFree1]] .
If n = 2, return AR .[[IsLockFree2]] .
If n = 4, return true .
If n = 8, return AR .[[IsLockFree8]] .
Return false .
Note
This function is an optimization primitive. The intuition is that if the atomic step of
an atomic primitive (compareExchange, load,
store, add, sub, and,
or, xor, or exchange) on a datum of size
n bytes will be performed without the surrounding agent
acquiring a lock outside the n bytes comprising the datum, then
Atomics.isLockFree(n ) will return true .
High-performance algorithms will use this function to determine whether to use locks or
atomic operations in critical sections . If an atomic
primitive is not lock-free then it is often more efficient for an algorithm to provide
its own locking.
Atomics.isLockFree(4) always returns true as that can be
supported on all known relevant hardware. Being able to assume this will generally
simplify programs.
Regardless of the value returned by this function, all atomic operations are guaranteed
to be atomic. For example, they will never have a visible operation take place in the
middle of the operation (e.g., "tearing").
25.4.9 Atomics.load ( typedArray , index )
This function performs the following steps when called:
Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray (typedArray ,
index ).
Perform ? RevalidateAtomicAccess (typedArray ,
byteIndexInBuffer ).
Let buffer be typedArray .[[ViewedArrayBuffer]] .
Let elementType be TypedArrayElementType (typedArray ).
Return GetValueFromBuffer (buffer ,
byteIndexInBuffer , elementType , true ,
seq-cst ).
25.4.10 Atomics.or ( typedArray , index ,
value )
This function performs the following steps when called:
Let or be a new read-modify-write modification
function with parameters (xBytes , yBytes )
that captures nothing and performs the following steps atomically when called:
Return ByteListBitwiseOp (|,
xBytes , yBytes ).
Return ? AtomicReadModifyWrite (typedArray ,
index , value , or ).
25.4.11 Atomics.store ( typedArray , index ,
value )
This function performs the following steps when called:
Let byteIndexInBuffer be ? ValidateAtomicAccessOnIntegerTypedArray (typedArray ,
index ).
If typedArray .[[ContentType]] is
bigint , let v be ? ToBigInt (value ).
Otherwise, let v be 𝔽 (? ToIntegerOrInfinity (value )).
Perform ? RevalidateAtomicAccess (typedArray ,
byteIndexInBuffer ).
Let buffer be typedArray .[[ViewedArrayBuffer]] .
Let elementType be TypedArrayElementType (typedArray ).
Perform SetValueInBuffer (buffer ,
byteIndexInBuffer , elementType , v ,
true , seq-cst ).
Return v .
25.4.12 Atomics.sub ( typedArray , index ,
value )
This function performs the following steps when called:
Let subtract be a new read-modify-write modification
function with parameters (xBytes , yBytes )
that captures typedArray and performs the following steps atomically when
called:
Let type be TypedArrayElementType (typedArray ).
Let isLittleEndian be the value of the [[LittleEndian]] field of the surrounding agent 's Agent
Record .
Let x be RawBytesToNumeric (type ,
xBytes , isLittleEndian ).
Let y be RawBytesToNumeric (type ,
yBytes , isLittleEndian ).
If x is a
Number , then
Let difference be Number::subtract (x ,
y ).
Else,
Assert : x is a
BigInt .
Let difference be BigInt::subtract (x ,
y ).
Let differenceBytes be NumericToRawBytes (type ,
difference , isLittleEndian ).
Assert : differenceBytes ,
xBytes , and yBytes have the same number of elements.
Return differenceBytes .
Return ? AtomicReadModifyWrite (typedArray ,
index , value , subtract ).
25.4.13 Atomics.wait ( typedArray , index ,
value , timeout )
This function puts the surrounding agent in a wait queue and suspends
it until notified or until the wait times out, returning a String differentiating those cases.
It performs the following steps when called:
Return ? DoWait (sync ,
typedArray , index , value , timeout ).
25.4.14 Atomics.waitAsync ( typedArray , index ,
value , timeout )
This function returns a Promise that is resolved when the calling agent is notified or the timeout is reached.
It performs the following steps when called:
Return ? DoWait (async ,
typedArray , index , value , timeout ).
25.4.15 Atomics.notify ( typedArray , index ,
count )
This function notifies some agents that are sleeping in the wait queue.
It performs the following steps when called:
Let taRecord be ? ValidateIntegerTypedArray (typedArray ,
true ).
Let byteIndexInBuffer be ? ValidateAtomicAccess (taRecord ,
index ).
If count is undefined , then
Let c be +∞.
Else,
Let intCount be ? ToIntegerOrInfinity (count ).
Let c be max (intCount , 0).
Let buffer be typedArray .[[ViewedArrayBuffer]] .
Let block be buffer .[[ArrayBufferData]] .
If IsSharedArrayBuffer (buffer )
is false , return +0 𝔽 .
Let WL be GetWaiterList (block ,
byteIndexInBuffer ).
Perform EnterCriticalSection (WL ).
Let S be RemoveWaiters (WL ,
c ).
For each element W of S , do
Perform NotifyWaiter (WL ,
W ).
Perform LeaveCriticalSection (WL ).
Let n be the number of elements in S .
Return 𝔽 (n ).
25.4.16 Atomics.xor ( typedArray , index ,
value )
This function performs the following steps when called:
Let xor be a new read-modify-write modification
function with parameters (xBytes , yBytes )
that captures nothing and performs the following steps atomically when called:
Return ByteListBitwiseOp (^,
xBytes , yBytes ).
Return ? AtomicReadModifyWrite (typedArray ,
index , value , xor ).
25.4.17 Atomics [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Atomics" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
25.5 The JSON Object
The JSON object:
is %JSON% .
is the initial value of the "JSON" property of the global
object .
is an ordinary
object .
contains two functions, parse and stringify, that are used to parse
and construct JSON texts.
has a [[Prototype]] internal slot whose value is %Object.prototype% .
does not have a [[Construct]] internal method; it cannot be used as a
constructor
with the new operator.
does not have a [[Call]] internal method; it cannot be invoked as a
function.
The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used in this
specification is exactly that described by ECMA-404. Conforming implementations of
JSON.parse and JSON.stringify must support the exact interchange format
described in the ECMA-404 specification without any deletions or extensions to the format.
25.5.1 JSON.parse ( text [ , reviver ] )
This function parses a JSON text (a JSON-formatted String) and produces an ECMAScript language value . The JSON
format represents literals, arrays, and objects with a syntax similar to the syntax for
ECMAScript literals, Array Initializers, and Object Initializers. After parsing, JSON objects
are realized as ECMAScript objects. JSON arrays are realized as ECMAScript Array instances. JSON
strings, numbers, booleans, and null are realized as ECMAScript Strings, Numbers, Booleans, and
null .
The optional reviver parameter is a function that takes two parameters, key
and value . It can filter and transform the results. It is called with each of the
key /value pairs produced by the parse, and its return value is used
instead of the original value. If it returns what it received, the structure is not modified. If
it returns undefined then the property is deleted from the result.
Let jsonString be ? ToString (text ).
Let unfiltered be ? ParseJSON (jsonString ).
If IsCallable (reviver ) is
true , then
Let root be OrdinaryObjectCreate (%Object.prototype% ).
Let rootName be the empty String.
Perform ! CreateDataPropertyOrThrow (root ,
rootName , unfiltered ).
Return ? InternalizeJSONProperty (root ,
rootName , reviver ).
Else,
Return unfiltered .
The "length" property of this function is 2 𝔽 .
25.5.1.1 ParseJSON ( text )
The abstract operation ParseJSON takes argument text (a String) and returns either
a normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
If StringToCodePoints (text )
is not a valid JSON text as specified in ECMA-404, throw a
SyntaxError exception.
Let scriptString be the string-concatenation of
"(" , text , and ");" .
Let script be ParseText (scriptString ,
Script ).
NOTE: The early
error rules defined in 13.2.5.1
have special handling for the above invocation of ParseText .
Assert :
script is a Parse Node .
Let result be ! Evaluation of script .
NOTE: The PropertyDefinitionEvaluation
semantics defined in 13.2.5.5
have special handling for the above evaluation.
Assert : result is either a String,
a Number, a Boolean, an Object that is defined by either an ArrayLiteral or an
ObjectLiteral , or
null .
Return result .
It is not permitted for a conforming implementation of JSON.parse to extend the
JSON grammars. If an implementation wishes to support a modified or extended JSON
interchange format it must do so by defining a different parse function.
Note 1
Valid JSON text is a subset of the ECMAScript PrimaryExpression syntax. Step
1 verifies that
jsonString conforms to that subset, and step 8 asserts that evaluation
returns a value of an appropriate type.
However, because 13.2.5.5
behaves differently during ParseJSON, the same source text can produce different
results when evaluated as a PrimaryExpression rather than as
JSON. Furthermore, the Early Error for duplicate "__proto__"
properties in object literals, which likewise does not apply during ParseJSON, means
that not all texts accepted by ParseJSON are valid as a PrimaryExpression , despite
matching the grammar.
Note 2
In the case where there are duplicate name Strings within an object, lexically
preceding values for the same key shall be overwritten.
25.5.1.2 InternalizeJSONProperty ( holder ,
name , reviver )
The abstract operation InternalizeJSONProperty takes arguments holder (an Object),
name (a String), and reviver (a function object ) and returns
either a normal completion
containing an ECMAScript language
value or a throw
completion .
Note
This algorithm intentionally does not throw an exception if either [[Delete]] or CreateDataProperty return
false .
It performs the following steps when called:
Let val be ? Get (holder , name ).
If val is an Object , then
Let isArray be ? IsArray (val ).
If isArray is true , then
Let len be ? LengthOfArrayLike (val ).
Let I be 0.
Repeat, while I < len ,
Let prop be ! ToString (𝔽 (I )).
Let newElement be ? InternalizeJSONProperty (val ,
prop , reviver ).
If newElement is undefined ,
then
Perform ? val .[[Delete]] (prop ).
Else,
Perform ? CreateDataProperty (val ,
prop , newElement ).
Set I to I + 1.
Else,
Let keys be ? EnumerableOwnProperties (val ,
key ).
For each String P of keys , do
Let newElement be ? InternalizeJSONProperty (val ,
P , reviver ).
If newElement is undefined ,
then
Perform ? val .[[Delete]] (P ).
Else,
Perform ? CreateDataProperty (val ,
P , newElement ).
Return ? Call (reviver ,
holder , « name , val »).
25.5.2 JSON.stringify ( value [ , replacer [ ,
space ] ] )
This function returns a String in UTF-16 encoded JSON format representing an ECMAScript language value , or
undefined . It can take three parameters. The value parameter is an
ECMAScript language value , which is
usually an object or array, although it can also be a String, Boolean, Number or
null . The optional replacer parameter is either a function that
alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts
as an inclusion list for selecting the object properties that will be stringified. The optional
space parameter is a
String or Number that allows the result to have white space injected into
it to improve human readability.
It performs the following steps when called:
Let stack be a new empty List .
Let indent be the empty String.
Let PropertyList be undefined .
Let ReplacerFunction be undefined .
If replacer is an Object , then
If IsCallable (replacer ) is
true , then
Set ReplacerFunction to replacer .
Else,
Let isArray be ? IsArray (replacer ).
If isArray is true , then
Set PropertyList to a new empty List .
Let len be ? LengthOfArrayLike (replacer ).
Let k be 0.
Repeat, while k < len ,
Let prop be ! ToString (𝔽 (k )).
Let v be ? Get (replacer ,
prop ).
Let item be undefined .
If v is
a String , then
Set item to v .
Else if v is
a Number , then
Set item to ! ToString (v ).
Else if v is an
Object , then
If v has a [[StringData]] or [[NumberData]] internal
slot, set item to ? ToString (v ).
If item is not undefined
and PropertyList does not contain
item , then
Append item to
PropertyList .
Set k to k + 1.
If space is an Object , then
If space has a [[NumberData]] internal slot,
then
Set space to ? ToNumber (space ).
Else if space has a [[StringData]] internal
slot, then
Set space to ? ToString (space ).
If space is a
Number , then
Let spaceMV be ! ToIntegerOrInfinity (space ).
Set spaceMV to min (10, spaceMV ).
If spaceMV < 1, let gap be the empty String; otherwise
let gap be the String value containing spaceMV occurrences
of the code unit 0x0020 (SPACE).
Else if space is a
String , then
If the length of space ≤ 10, let gap be space ;
otherwise let gap be the substring of
space from 0 to 10.
Else,
Let gap be the empty String.
Let wrapper be OrdinaryObjectCreate (%Object.prototype% ).
Perform ! CreateDataPropertyOrThrow (wrapper ,
the empty String, value ).
Let state be the JSON Serialization
Record { [[ReplacerFunction]] :
ReplacerFunction , [[Stack]] : stack , [[Indent]] : indent , [[Gap]] :
gap , [[PropertyList]] :
PropertyList }.
Return ? SerializeJSONProperty (state , the
empty String, wrapper ).
The "length" property of this function is 3 𝔽 .
Note 1
JSON structures are allowed to be nested to any depth, but they must be acyclic. If
value is or contains a cyclic structure, then this function must throw a
TypeError exception. This is an example of a value that cannot be
stringified:
a = [];
a[0 ] = a;
my_text = JSON .stringify (a);
Note 2
Symbolic primitive values are rendered as follows:
The null value is rendered in JSON text as the String value
"null" .
The undefined value is not rendered.
The true value is rendered in JSON text as the String value
"true" .
The false value is rendered in JSON text as the String value
"false" .
Note 3
String values are wrapped in QUOTATION MARK (") code units. The code units
" and \ are escaped with \ prefixes. Control
characters code units are replaced with escape sequences \uHHHH, or with
the shorter forms, \b (BACKSPACE), \f (FORM FEED),
\n (LINE FEED), \r (CARRIAGE RETURN), \t
(CHARACTER TABULATION).
Note 4
Finite numbers
are stringified as if by calling ToString (number ).
NaN and Infinity regardless of sign are
represented as the String value "null" .
Note 5
Values that do not have a JSON representation (such as undefined and
functions) do not produce a String. Instead they produce the
undefined value. In arrays these values are represented as the String
value "null" . In objects an unrepresentable value causes the property
to be excluded from stringification.
Note 6
An object is rendered as U+007B (LEFT CURLY BRACKET) followed by zero or more properties,
separated with a U+002C (COMMA), closed with a U+007D (RIGHT CURLY BRACKET). A property
is a quoted String representing the property name , a U+003A (COLON), and then
the stringified property value. An array is rendered as an opening U+005B (LEFT SQUARE
BRACKET) followed by zero or more values, separated with a U+002C (COMMA), closed with a
U+005D (RIGHT SQUARE BRACKET).
25.5.2.1 JSON Serialization Record
A JSON Serialization Record is
a Record value used to
enable serialization to the JSON format.
JSON Serialization Records have the fields listed in Table 80 .
Table 80: JSON Serialization
Record Fields
Field Name
Value
Meaning
[[ReplacerFunction]]
a function object or
undefined
A function that can supply replacement values for object properties
(from JSON.stringify's replacer parameter).
[[PropertyList]]
either a List
of Strings or undefined
The names of properties to include when serializing a non-array object
(from JSON.stringify's replacer parameter).
[[Gap]]
a String
The unit of indentation (from JSON.stringify's space
parameter).
[[Stack]]
a List
of Objects
The set of nested objects that are in the process of being serialized.
Used to detect cyclic structures.
[[Indent]]
a String
The current indentation.
25.5.2.2 SerializeJSONProperty ( state ,
key , holder )
The abstract operation SerializeJSONProperty takes arguments state (a JSON Serialization Record ),
key (a String), and holder (an Object) and returns either a normal completion
containing either a String or undefined , or a
throw completion . It
performs the following steps when called:
Let value be ? Get (holder , key ).
If value is an Object or value
is a
BigInt , then
Let toJSON be ? GetV (value ,
"toJSON" ).
If IsCallable (toJSON )
is true , then
Set value to ? Call (toJSON ,
value , « key »).
If state .[[ReplacerFunction]] is not
undefined , then
Set value to ? Call (state .[[ReplacerFunction]] , holder , «
key , value »).
If value is an Object , then
If value has a [[NumberData]] internal
slot, then
Set value to ? ToNumber (value ).
Else if value has a [[StringData]]
internal slot, then
Set value to ? ToString (value ).
Else if value has a [[BooleanData]]
internal slot, then
Set value to value .[[BooleanData]] .
Else if value has a [[BigIntData]]
internal slot, then
Set value to value .[[BigIntData]] .
If value is null , return "null" .
If value is true , return "true" .
If value is false , return "false" .
If value is a
String , return QuoteJSONString (value ).
If value is a
Number , then
If value is finite , return ! ToString (value ).
Return "null" .
If value is a
BigInt , throw a TypeError exception.
If value is an Object and IsCallable (value ) is
false , then
Let isArray be ? IsArray (value ).
If isArray is true , return ? SerializeJSONArray (state ,
value ).
Return ? SerializeJSONObject (state ,
value ).
Return undefined .
25.5.2.3 QuoteJSONString ( value )
The abstract operation QuoteJSONString takes argument value (a String) and returns
a String. It wraps value in 0x0022 (QUOTATION MARK) code units and escapes
certain other code units within it. This operation interprets value as a sequence
of UTF-16 encoded code points, as described in 6.1.4 . It performs
the following steps when called:
Let product be the String value consisting solely of the code unit 0x0022
(QUOTATION MARK).
For each code point C of StringToCodePoints (value ),
do
If C is listed in the “Code Point” column of Table 81 ,
then
Set product to the string-concatenation
of product and the escape sequence for C as
specified in the “Escape Sequence” column of the corresponding row.
Else if C has a numeric value less than 0x0020 (SPACE) or
C has the same numeric value as a leading surrogate or
trailing surrogate , then
Let unit be the code unit whose numeric value is the
numeric value of C .
Set product to the string-concatenation
of product and UnicodeEscape (unit ).
Else,
Set product to the string-concatenation
of product and UTF16EncodeCodePoint (C ).
Set product to the string-concatenation of
product and the code unit 0x0022 (QUOTATION MARK).
Return product .
Table 81: JSON Single Character Escape Sequences
Code Point
Unicode Character Name
Escape Sequence
U+0008
BACKSPACE
\b
U+0009
CHARACTER TABULATION
\t
U+000A
LINE FEED (LF)
\n
U+000C
FORM FEED (FF)
\f
U+000D
CARRIAGE RETURN (CR)
\r
U+0022
QUOTATION MARK
\"
U+005C
REVERSE SOLIDUS
\\
25.5.2.4 UnicodeEscape ( C )
The abstract operation UnicodeEscape takes argument C (a code unit) and returns a
String. It represents C as a Unicode escape sequence. It performs the following
steps when called:
Let n be the numeric value of C .
Assert :
n ≤ 0xFFFF.
Let hex be the String representation of n , formatted as a
lowercase hexadecimal number.
Return the string-concatenation of the code
unit 0x005C (REVERSE SOLIDUS), "u" , and StringPad (hex , 4,
"0" , start ).
25.5.2.5 SerializeJSONObject ( state ,
value )
The abstract operation SerializeJSONObject takes arguments state (a JSON Serialization Record ) and
value (an Object) and returns either a normal completion
containing a String or a throw completion . It
serializes an object. It performs the following steps when called:
If state .[[Stack]] contains value ,
throw a TypeError exception because the structure is cyclical.
Append value to state .[[Stack]] .
Let stepBack be state .[[Indent]] .
Set state .[[Indent]] to the string-concatenation of
state .[[Indent]] and state .[[Gap]] .
If state .[[PropertyList]] is not
undefined , then
Let K be state .[[PropertyList]] .
Else,
Let K be ? EnumerableOwnProperties (value ,
key ).
Let partial be a new empty List .
For each element P of K , do
Let strP be ? SerializeJSONProperty (state ,
P , value ).
If strP is not undefined , then
Let member be QuoteJSONString (P ).
Set member to the string-concatenation
of member and ":" .
If state .[[Gap]] is not the
empty String, then
Set member to the string-concatenation
of member and the code unit 0x0020 (SPACE).
Set member to the string-concatenation
of member and strP .
Append member to partial .
If partial is empty, then
Let final be "{}" .
Else,
If state .[[Gap]] is the empty String,
then
Let properties be the String value formed by
concatenating all the element Strings of partial with
each adjacent pair of Strings separated with the code unit 0x002C
(COMMA). A comma is not inserted either before the first String or
after the last String.
Let final be the string-concatenation
of "{" , properties , and
"}" .
Else,
Let separator be the string-concatenation
of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED),
and state .[[Indent]] .
Let properties be the String value formed by
concatenating all the element Strings of partial with
each adjacent pair of Strings separated with separator .
The separator String is not inserted either before the
first String or after the last String.
Let final be the string-concatenation
of "{" , the code unit 0x000A (LINE FEED),
state .[[Indent]] ,
properties , the code unit 0x000A (LINE FEED),
stepBack , and "}" .
Remove the last element of state .[[Stack]] .
Set state .[[Indent]] to stepBack .
Return final .
25.5.2.6 SerializeJSONArray ( state , value
)
The abstract operation SerializeJSONArray takes arguments state (a JSON Serialization Record ) and
value (an ECMAScript language value ) and
returns either a normal completion
containing a String or a throw completion . It
serializes an array. It performs the following steps when called:
If state .[[Stack]] contains value ,
throw a TypeError exception because the structure is cyclical.
Append value to state .[[Stack]] .
Let stepBack be state .[[Indent]] .
Set state .[[Indent]] to the string-concatenation of
state .[[Indent]] and state .[[Gap]] .
Let partial be a new empty List .
Let len be ? LengthOfArrayLike (value ).
Let index be 0.
Repeat, while index < len ,
Let strP be ? SerializeJSONProperty (state ,
! ToString (𝔽 (index )),
value ).
If strP is undefined , then
Append "null" to partial .
Else,
Append strP to partial .
Set index to index + 1.
If partial is empty, then
Let final be "[]" .
Else,
If state .[[Gap]] is the empty String,
then
Let properties be the String value formed by
concatenating all the element Strings of partial with
each adjacent pair of Strings separated with the code unit 0x002C
(COMMA). A comma is not inserted either before the first String or
after the last String.
Let final be the string-concatenation
of "[" , properties , and
"]" .
Else,
Let separator be the string-concatenation
of the code unit 0x002C (COMMA), the code unit 0x000A (LINE FEED),
and state .[[Indent]] .
Let properties be the String value formed by
concatenating all the element Strings of partial with
each adjacent pair of Strings separated with separator .
The separator String is not inserted either before the
first String or after the last String.
Let final be the string-concatenation
of "[" , the code unit 0x000A (LINE FEED),
state .[[Indent]] ,
properties , the code unit 0x000A (LINE FEED),
stepBack , and "]" .
Remove the last element of state .[[Stack]] .
Set state .[[Indent]] to stepBack .
Return final .
Note
The representation of arrays includes only the elements in the interval
from +0 𝔽 (inclusive) to array.length
(exclusive). Properties whose keys are not array indices are excluded
from the stringification. An array is stringified as an opening LEFT SQUARE BRACKET,
elements separated by COMMA, and a closing RIGHT SQUARE BRACKET.
25.5.3 JSON [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "JSON" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
26 Managing Memory
26.1 WeakRef Objects
A WeakRef is an object that is used to refer
to a target object or symbol without preserving it from garbage collection. WeakRefs can be dereferenced to allow access
to the target value, if the target hasn't been reclaimed by garbage collection.
26.1.1 The WeakRef Constructor
The WeakRef constructor :
is %WeakRef% .
is the initial value of the "WeakRef" property of the global
object .
creates and initializes a new WeakRef when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
WeakRef behaviour must include a super call to the
WeakRef constructor to create and initialize the subclass
instance with the internal state necessary to support the WeakRef.prototype
built-in methods.
26.1.1.1 WeakRef ( target )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
If CanBeHeldWeakly (target )
is false , throw a TypeError exception.
Let weakRef be ? OrdinaryCreateFromConstructor (NewTarget,
"%WeakRef.prototype%" , « [[WeakRefTarget]] »).
Perform AddToKeptObjects (target ).
Set weakRef .[[WeakRefTarget]] to
target .
Return weakRef .
26.1.2 Properties of the WeakRef Constructor
The WeakRef constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
26.1.2.1 WeakRef.prototype
The initial value of WeakRef.prototype is the WeakRef prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
26.1.3 Properties of the WeakRef Prototype Object
The WeakRef prototype object :
26.1.3.1 WeakRef.prototype.constructor
The initial value of WeakRef.prototype.constructor is %WeakRef% .
26.1.3.2 WeakRef.prototype.deref ( )
This method performs the following steps when called:
Let weakRef be the this value.
Perform ? RequireInternalSlot (weakRef ,
[[WeakRefTarget]] ).
Return WeakRefDeref (weakRef ).
Note
If the WeakRef returns a
target value that is not undefined , then this
target value should not be garbage collected until the current execution
of ECMAScript code has completed. The AddToKeptObjects
operation makes sure read consistency is maintained.
let target = { foo ( ) {} };
let weakRef = new WeakRef (target);
if (weakRef.deref ()) {
weakRef.deref ().foo ();
}
In the above example, if the first deref does not evaluate to
undefined then the second deref cannot either.
26.1.3.3 WeakRef.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "WeakRef" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
26.1.4 WeakRef Abstract Operations
26.1.4.1 WeakRefDeref ( weakRef )
The abstract operation WeakRefDeref takes argument weakRef (a WeakRef ) and returns an ECMAScript language value . It
performs the following steps when called:
Let target be weakRef .[[WeakRefTarget]] .
If target is not empty , then
Perform AddToKeptObjects (target ).
Return target .
Return undefined .
Note
This abstract operation is defined separately from WeakRef.prototype.deref strictly
to make it possible to succinctly define liveness.
26.1.5 Properties of WeakRef Instances
WeakRef instances are ordinary
objects that inherit properties from the WeakRef prototype
object . WeakRef instances also have a [[WeakRefTarget]] internal slot.
26.2 FinalizationRegistry Objects
A FinalizationRegistry is an
object that manages registration and unregistration of cleanup operations that are performed when
target objects and symbols are garbage collected.
26.2.1 The FinalizationRegistry Constructor
The FinalizationRegistry constructor :
is %FinalizationRegistry% .
is the initial value of the "FinalizationRegistry" property of the
global
object .
creates and initializes a new FinalizationRegistry when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
FinalizationRegistry behaviour must include a super call to the
FinalizationRegistry constructor to create and initialize the subclass
instance with the internal state necessary to support the
FinalizationRegistry.prototype built-in methods.
26.2.1.1 FinalizationRegistry ( cleanupCallback )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
If IsCallable (cleanupCallback )
is false , throw a TypeError exception.
Let finalizationRegistry be ? OrdinaryCreateFromConstructor (NewTarget,
"%FinalizationRegistry.prototype%" , « [[Realm]] , [[CleanupCallback]] ,
[[Cells]] »).
Let fn be the active function object .
Set finalizationRegistry .[[Realm]] to
fn .[[Realm]] .
Set finalizationRegistry .[[CleanupCallback]] to
HostMakeJobCallback (cleanupCallback ).
Set finalizationRegistry .[[Cells]] to a new
empty List .
Return finalizationRegistry .
26.2.2 Properties of the FinalizationRegistry Constructor
The FinalizationRegistry
constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
26.2.2.1 FinalizationRegistry.prototype
The initial value of FinalizationRegistry.prototype is the FinalizationRegistry
prototype object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
26.2.3 Properties of the FinalizationRegistry Prototype Object
The FinalizationRegistry prototype object :
is %FinalizationRegistry.prototype% .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is an ordinary
object .
does not have [[Cells]] and [[CleanupCallback]] internal slots.
26.2.3.1 FinalizationRegistry.prototype.constructor
The initial value of FinalizationRegistry.prototype.constructor is %FinalizationRegistry% .
26.2.3.2 FinalizationRegistry.prototype.register (
target , heldValue [ , unregisterToken ] )
This method performs the following steps when called:
Let finalizationRegistry be the this value.
Perform ? RequireInternalSlot (finalizationRegistry ,
[[Cells]] ).
If CanBeHeldWeakly (target )
is false , throw a TypeError exception.
If SameValue (target ,
heldValue ) is true , throw a
TypeError exception.
If CanBeHeldWeakly (unregisterToken )
is false , then
If unregisterToken is not undefined , throw a
TypeError exception.
Set unregisterToken to empty .
Let cell be the Record { [[WeakRefTarget]] : target , [[HeldValue]] : heldValue , [[UnregisterToken]] : unregisterToken }.
Append cell to finalizationRegistry .[[Cells]] .
Return undefined .
Note
Based on the algorithms and definitions in this specification, cell .[[HeldValue]] is live when
finalizationRegistry .[[Cells]] contains
cell ; however, this does not necessarily mean that cell .[[UnregisterToken]] or cell .[[Target]] are live . For example,
registering an object with itself as its unregister token would not keep the object
alive forever.
26.2.3.3 FinalizationRegistry.prototype.unregister (
unregisterToken )
This method performs the following steps when called:
Let finalizationRegistry be the this value.
Perform ? RequireInternalSlot (finalizationRegistry ,
[[Cells]] ).
If CanBeHeldWeakly (unregisterToken )
is false , throw a TypeError exception.
Let removed be false .
For each Record { [[WeakRefTarget]] , [[HeldValue]] ,
[[UnregisterToken]] } cell of
finalizationRegistry .[[Cells]] , do
If cell .[[UnregisterToken]] is not
empty and SameValue (cell .[[UnregisterToken]] , unregisterToken ) is
true , then
Remove cell from finalizationRegistry .[[Cells]] .
Set removed to true .
Return removed .
26.2.3.4 FinalizationRegistry.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "FinalizationRegistry" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
26.2.4 Properties of FinalizationRegistry Instances
FinalizationRegistry
instances are ordinary objects that inherit properties from the
FinalizationRegistry
prototype object . FinalizationRegistry
instances also have [[Cells]] and [[CleanupCallback]] internal slots.
27 Control Abstraction Objects
27.1 Iteration
27.1.1 Common Iteration Interfaces
An interface is a set of property keys whose associated values match a
specific specification. Any object that provides all the properties as described by an
interface's specification conforms to that interface. An interface is not represented
by a distinct object. There may be many separately implemented objects that conform to any
interface. An individual object may conform to multiple interfaces.
27.1.1.1 The Iterable Interface
The iterable interface includes the property described in Table 82 :
Table 82: Iterable Interface Required
Properties
27.1.1.2 The Iterator Interface
An object that implements the iterator
interface must include the property in Table 83 . Such
objects may also implement the properties in Table 84 .
Table 83: Iterator Interface Required
Properties
Note 1
Arguments may be passed to the next function but their interpretation
and validity is dependent upon the target iterator. The for-of statement and other
common users of iterators do not pass any arguments, so iterator objects that expect
to be used in such a manner must be prepared to deal with being called with no
arguments.
Table 84: Iterator Interface Optional
Properties
Property
Value
Requirements
"return"
a function that returns an IteratorResult
object
The returned object must conform to the IteratorResult
interface . Invoking this method notifies the
iterator object
that the caller does not intend to make any more next
method calls to the iterator . The
returned IteratorResult
object will typically have a
"done" property whose value is
true , and a "value" property with
the value passed as the argument of the return method.
However, this requirement is not enforced.
"throw"
a function that returns an IteratorResult
object
The returned object must conform to the IteratorResult
interface . Invoking this method notifies the
iterator object
that the caller has detected an error condition. The argument may be
used to identify the error condition and typically will be an exception
object. A typical response is to throw the value passed as
the argument. If the method does not throw, the returned
IteratorResult
object will typically have a
"done" property whose value is
true .
Note 2
Typically callers of these methods should check for their existence before invoking
them. Certain ECMAScript language features including
for-of, yield*, and array destructuring call
these methods after performing an existence check. Most ECMAScript library functions
that accept iterable objects as arguments
also conditionally call them.
27.1.1.3 The Async Iterable Interface
The async iterable interface includes the properties described in
Table
85 :
Table 85: Async Iterable Interface Required
Properties
27.1.1.4 The Async Iterator Interface
An object that implements the async iterator interface must include the properties in Table 86 . Such objects may also
implement the properties in Table 87 .
Table 86: Async Iterator Interface Required
Properties
Property
Value
Requirements
"next"
a function that returns a promise for an IteratorResult
object
The returned promise, when fulfilled, must fulfill with an object
that conforms to the IteratorResult
interface . If a previous call to the
next method of an async
iterator has returned a promise for an
IteratorResult
object whose "done"
property is true , then all subsequent calls to
the next method of that object should also return a
promise for an IteratorResult
object whose "done"
property is true . However, this requirement is
not enforced.
Additionally, the IteratorResult
object that serves as a fulfillment value
should have a "value" property whose value is not
a promise (or "thenable"). However, this requirement is also not
enforced.
Note 1
Arguments may be passed to the next function but their interpretation
and validity is dependent upon the target async iterator. The
for-await-of statement and other common users
of async iterators do not pass any arguments, so async iterator objects that expect
to be used in such a manner must be prepared to deal with being called with no
arguments.
Table 87: Async Iterator Interface Optional
Properties
Property
Value
Requirements
"return"
a function that returns a promise for an IteratorResult
object
The returned promise, when fulfilled, must fulfill with an object
that conforms to the IteratorResult
interface . Invoking this method notifies the
async iterator
object that the caller does not intend to
make any more next method calls to the async
iterator . The returned promise will fulfill
with an IteratorResult
object which will typically have a
"done" property whose value is
true , and a "value" property
with the value passed as the argument of the return
method. However, this requirement is not enforced.
Additionally, the IteratorResult
object that serves as a fulfillment value
should have a "value" property whose value is not
a promise (or "thenable"). If the argument value is used in the
typical manner, then if it is a rejected promise, a promise rejected
with the same reason should be returned; if it is a fulfilled
promise, then its fulfillment value should be used as the
"value" property of the returned promise's
IteratorResult
object fulfillment value. However, these
requirements are also not enforced.
"throw"
a function that returns a promise for an IteratorResult
object
The returned promise, when fulfilled, must fulfill with an object
that conforms to the IteratorResult
interface . Invoking this method notifies the
async iterator
object that the caller has detected an error
condition. The argument may be used to identify the error condition
and typically will be an exception object. A typical response is to
return a rejected promise which rejects with the value passed as the
argument.
If the returned promise is fulfilled, the IteratorResult
object fulfillment value will typically have
a "done" property whose value is
true . Additionally, it should have a
"value" property whose value is not a promise (or
"thenable"), but this requirement is not enforced.
Note 2
Typically callers of these methods should check for their existence before invoking
them. Certain ECMAScript language features including
for-await-of and yield* call
these methods after performing an existence check.
27.1.1.5 The IteratorResult Interface
The IteratorResult
interface includes the properties listed in Table 88 :
Table 88: IteratorResult Interface Properties
Property
Value
Requirements
"done"
a Boolean
This is the result status of an iterator
next method call. If the end of the iterator was
reached "done" is true . If the end
was not reached "done" is false
and a value is available. If a "done" property
(either own or inherited) does not exist, it is considered to have the
value false .
"value"
an ECMAScript language
value
If done is false , this is the current iteration
element value. If done is true , this is the return
value of the iterator , if it
supplied one. If the iterator does not
have a return value, "value" is
undefined . In that case, the
"value" property may be absent from the conforming
object if it does not inherit an explicit "value"
property.
27.1.2 Iterator Helper Objects
An Iterator Helper object is an
ordinary
object that represents a lazy transformation of some specific source
iterator object . There is not a named
constructor
for Iterator Helper objects. Instead, Iterator Helper objects are created by calling certain
methods of Iterator instance objects.
27.1.2.1 The %IteratorHelperPrototype% Object
The %IteratorHelperPrototype% object:
27.1.2.1.1 %IteratorHelperPrototype%.next ( )
Return ? GeneratorResume (this
value, undefined , "Iterator Helper" ).
27.1.2.1.2 %IteratorHelperPrototype%.return ( )
Let O be this value.
Perform ? RequireInternalSlot (O ,
[[UnderlyingIterator]] ).
Assert : O has a [[GeneratorState]] internal slot.
If O .[[GeneratorState]] is
suspended-start , then
Set O .[[GeneratorState]] to
completed .
NOTE: Once a generator enters the completed state it never leaves it and
its associated execution
context is never resumed. Any execution state
associated with O can be discarded at this point.
Perform ? IteratorClose (O .[[UnderlyingIterator]] , NormalCompletion (unused )).
Return CreateIteratorResultObject (undefined ,
true ).
Let C be ReturnCompletion (undefined ).
Return ? GeneratorResumeAbrupt (O ,
C , "Iterator Helper" ).
27.1.2.1.3 %IteratorHelperPrototype% [ %Symbol.toStringTag%
]
The initial value of the %Symbol.toStringTag% property is
the String value "Iterator Helper" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
true }.
27.1.3 Iterator Objects
27.1.3.1 The Iterator Constructor
The Iterator constructor :
is %Iterator% .
is the initial value of the "Iterator" property of the global
object .
is designed to be subclassable. It may be used as the value of an
extends clause of a class definition.
27.1.3.1.1 Iterator ( )
This function performs the following steps when called:
If NewTarget is either undefined or the active function object ,
throw a TypeError exception.
Return ? OrdinaryCreateFromConstructor (NewTarget,
"%Iterator.prototype%" ).
27.1.3.2 Properties of the Iterator Constructor
The Iterator constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
27.1.3.2.1 Iterator.from ( O )
Let iteratorRecord be ? GetIteratorFlattenable (O ,
iterate-string-primitives ).
Let hasInstance be ? OrdinaryHasInstance (%Iterator% ,
iteratorRecord .[[Iterator]] ).
If hasInstance is true , then
Return iteratorRecord .[[Iterator]] .
Let wrapper be OrdinaryObjectCreate (%WrapForValidIteratorPrototype% ,
« [[Iterated]] »).
Set wrapper .[[Iterated]] to
iteratorRecord .
Return wrapper .
27.1.3.2.1.1 The %WrapForValidIteratorPrototype% Object
The %WrapForValidIteratorPrototype% object:
27.1.3.2.1.1.1 %WrapForValidIteratorPrototype%.next
( )
Let O be this value.
Perform ? RequireInternalSlot (O ,
[[Iterated]] ).
Let iteratorRecord be O .[[Iterated]] .
Return ? Call (iteratorRecord .[[NextMethod]] , iteratorRecord .[[Iterator]] ).
27.1.3.2.1.1.2
%WrapForValidIteratorPrototype%.return ( )
Let O be this value.
Perform ? RequireInternalSlot (O ,
[[Iterated]] ).
Let iterator be O .[[Iterated]] .[[Iterator]] .
Assert : iterator
is an Object .
Let returnMethod be ? GetMethod (iterator ,
"return" ).
If returnMethod is undefined , then
Return CreateIteratorResultObject (undefined ,
true ).
Return ? Call (returnMethod ,
iterator ).
27.1.3.2.2 Iterator.prototype
The initial value of Iterator.prototype is the Iterator prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] :
false , [[Configurable]] :
false }.
27.1.4 Properties of the Iterator Prototype Object
The Iterator prototype object :
Note
All objects defined in this specification that implement the iterator interface also inherit
from %Iterator.prototype%. ECMAScript code may also define objects that inherit from
%Iterator.prototype%. %Iterator.prototype% provides a place where additional methods
that are applicable to all iterator objects may be added.
The following expression is one way that ECMAScript code can access the
%Iterator.prototype% object:
Object .getPrototypeOf (Object .getPrototypeOf ([][Symbol .iterator ]()))
27.1.4.1 Iterator.prototype.constructor
Iterator.prototype.constructor is an accessor property with
attributes { [[Enumerable]] : false , [[Configurable]] : true }. The [[Get]] and [[Set]] attributes are defined
as follows:
27.1.4.1.1 get Iterator.prototype.constructor
The value of the [[Get]] attribute is a built-in function that
requires no arguments. It performs the following steps when called:
Return %Iterator% .
27.1.4.1.2 set Iterator.prototype.constructor
The value of the [[Set]] attribute is a built-in function that
takes an argument v . It performs the following steps when called:
Perform ? SetterThatIgnoresPrototypeProperties (this
value, %Iterator.prototype% ,
"constructor" , v ).
Return undefined .
Note
Unlike the "constructor" property on most built-in prototypes, for
web-compatibility reasons this property must be an accessor.
27.1.4.2 Iterator.prototype.drop ( limit )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
Let numLimit be Completion (ToNumber (limit )).
IfAbruptCloseIterator (numLimit ,
iterated ).
If numLimit is NaN , then
Let error be ThrowCompletion (a newly
created RangeError object).
Return ? IteratorClose (iterated ,
error ).
Let integerLimit be ! ToIntegerOrInfinity (numLimit ).
If integerLimit < 0, then
Let error be ThrowCompletion (a newly
created RangeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let closure be a new Abstract Closure
with no parameters that captures iterated and integerLimit and
performs the following steps when called:
Let remaining be integerLimit .
Repeat, while remaining > 0,
If remaining ≠ +∞, then
Set remaining to remaining - 1.
Let next be ? IteratorStep (iterated ).
If next is done , return ReturnCompletion (undefined ).
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return ReturnCompletion (undefined ).
Let completion be Completion (Yield (value )).
IfAbruptCloseIterator (completion ,
iterated ).
Let result be CreateIteratorFromClosure (closure ,
"Iterator Helper" , %IteratorHelperPrototype% ,
« [[UnderlyingIterator]] »).
Set result .[[UnderlyingIterator]] to
iterated .
Return result .
27.1.4.3 Iterator.prototype.every ( predicate )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (predicate ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return
true .
Let result be Completion (Call (predicate ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (result ,
iterated ).
If ToBoolean (result ) is
false , return ? IteratorClose (iterated ,
NormalCompletion (false )).
Set counter to counter + 1.
27.1.4.4 Iterator.prototype.filter ( predicate )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (predicate ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let closure be a new Abstract Closure
with no parameters that captures iterated and predicate and
performs the following steps when called:
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return ReturnCompletion (undefined ).
Let selected be Completion (Call (predicate ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (selected ,
iterated ).
If ToBoolean (selected )
is true , then
Let completion be Completion (Yield (value )).
IfAbruptCloseIterator (completion ,
iterated ).
Set counter to counter + 1.
Let result be CreateIteratorFromClosure (closure ,
"Iterator Helper" , %IteratorHelperPrototype% ,
« [[UnderlyingIterator]] »).
Set result .[[UnderlyingIterator]] to
iterated .
Return result .
27.1.4.5 Iterator.prototype.find ( predicate )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (predicate ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return
undefined .
Let result be Completion (Call (predicate ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (result ,
iterated ).
If ToBoolean (result ) is
true , return ? IteratorClose (iterated ,
NormalCompletion (value )).
Set counter to counter + 1.
27.1.4.6 Iterator.prototype.flatMap ( mapper )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (mapper ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let closure be a new Abstract Closure
with no parameters that captures iterated and mapper and
performs the following steps when called:
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return ReturnCompletion (undefined ).
Let mapped be Completion (Call (mapper ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (mapped ,
iterated ).
Let innerIterator be Completion (GetIteratorFlattenable (mapped ,
reject-primitives )).
IfAbruptCloseIterator (innerIterator ,
iterated ).
Let innerAlive be true .
Repeat, while innerAlive is true ,
Let innerValue be Completion (IteratorStepValue (innerIterator )).
IfAbruptCloseIterator (innerValue ,
iterated ).
If innerValue is done ,
then
Set innerAlive to
false .
Else,
Let completion be Completion (Yield (innerValue )).
If completion is an abrupt
completion , then
Let backupCompletion be Completion (IteratorClose (innerIterator ,
completion )).
IfAbruptCloseIterator (backupCompletion ,
iterated ).
Return ? IteratorClose (iterated ,
completion ).
Set counter to counter + 1.
Let result be CreateIteratorFromClosure (closure ,
"Iterator Helper" , %IteratorHelperPrototype% ,
« [[UnderlyingIterator]] »).
Set result .[[UnderlyingIterator]] to
iterated .
Return result .
27.1.4.7 Iterator.prototype.forEach ( procedure )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (procedure ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return
undefined .
Let result be Completion (Call (procedure ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (result ,
iterated ).
Set counter to counter + 1.
27.1.4.8 Iterator.prototype.map ( mapper )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (mapper ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let closure be a new Abstract Closure
with no parameters that captures iterated and mapper and
performs the following steps when called:
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return ReturnCompletion (undefined ).
Let mapped be Completion (Call (mapper ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (mapped ,
iterated ).
Let completion be Completion (Yield (mapped )).
IfAbruptCloseIterator (completion ,
iterated ).
Set counter to counter + 1.
Let result be CreateIteratorFromClosure (closure ,
"Iterator Helper" , %IteratorHelperPrototype% ,
« [[UnderlyingIterator]] »).
Set result .[[UnderlyingIterator]] to
iterated .
Return result .
27.1.4.9 Iterator.prototype.reduce ( reducer [ ,
initialValue ] )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (reducer ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
If initialValue is not present, then
Let accumulator be ? IteratorStepValue (iterated ).
If accumulator is done , throw a
TypeError exception.
Let counter be 1.
Else,
Let accumulator be initialValue .
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return
accumulator .
Let result be Completion (Call (reducer ,
undefined , « accumulator , value ,
𝔽 (counter ) »)).
IfAbruptCloseIterator (result ,
iterated ).
Set accumulator to result .
Set counter to counter + 1.
27.1.4.10 Iterator.prototype.some ( predicate )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
If IsCallable (predicate ) is
false , then
Let error be ThrowCompletion (a newly
created TypeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let counter be 0.
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return
false .
Let result be Completion (Call (predicate ,
undefined , « value , 𝔽 (counter ) »)).
IfAbruptCloseIterator (result ,
iterated ).
If ToBoolean (result ) is
true , return ? IteratorClose (iterated ,
NormalCompletion (true )).
Set counter to counter + 1.
27.1.4.11 Iterator.prototype.take ( limit )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be the Iterator Record {
[[Iterator]] : O , [[NextMethod]] : undefined , [[Done]] : false }.
Let numLimit be Completion (ToNumber (limit )).
IfAbruptCloseIterator (numLimit ,
iterated ).
If numLimit is NaN , then
Let error be ThrowCompletion (a newly
created RangeError object).
Return ? IteratorClose (iterated ,
error ).
Let integerLimit be ! ToIntegerOrInfinity (numLimit ).
If integerLimit < 0, then
Let error be ThrowCompletion (a newly
created RangeError object).
Return ? IteratorClose (iterated ,
error ).
Set iterated to ? GetIteratorDirect (O ).
Let closure be a new Abstract Closure
with no parameters that captures iterated and integerLimit and
performs the following steps when called:
Let remaining be integerLimit .
Repeat,
If remaining = 0, then
Return ? IteratorClose (iterated ,
ReturnCompletion (undefined )).
If remaining ≠ +∞, then
Set remaining to remaining - 1.
Let value be ? IteratorStepValue (iterated ).
If value is done , return ReturnCompletion (undefined ).
Let completion be Completion (Yield (value )).
IfAbruptCloseIterator (completion ,
iterated ).
Let result be CreateIteratorFromClosure (closure ,
"Iterator Helper" , %IteratorHelperPrototype% ,
« [[UnderlyingIterator]] »).
Set result .[[UnderlyingIterator]] to
iterated .
Return result .
27.1.4.12 Iterator.prototype.toArray ( )
This method performs the following steps when called:
Let O be the this value.
If O is not an Object , throw a
TypeError exception.
Let iterated be ? GetIteratorDirect (O ).
Let items be a new empty List .
Repeat,
Let value be ? IteratorStepValue (iterated ).
If value is done , return CreateArrayFromList (items ).
Append value to items .
27.1.4.13 Iterator.prototype [ %Symbol.iterator% ] ( )
This function performs the following steps when called:
Return the this value.
The value of the "name" property of this function is
"[Symbol.iterator]" .
27.1.4.14 Iterator.prototype [ %Symbol.toStringTag% ]
Iterator.prototype[%Symbol.toStringTag%] is an accessor property with
attributes { [[Enumerable]] : false , [[Configurable]] : true }. The [[Get]] and [[Set]] attributes are defined
as follows:
27.1.4.14.1 get Iterator.prototype [ %Symbol.toStringTag% ]
The value of the [[Get]] attribute is a built-in function that
requires no arguments. It performs the following steps when called:
Return "Iterator" .
27.1.4.14.2 set Iterator.prototype [ %Symbol.toStringTag% ]
The value of the [[Set]] attribute is a built-in function that
takes an argument v . It performs the following steps when called:
Perform ? SetterThatIgnoresPrototypeProperties (this
value, %Iterator.prototype% ,
%Symbol.toStringTag% ,
v ).
Return undefined .
Note
Unlike the %Symbol.toStringTag% property
on most built-in prototypes, for web-compatibility reasons this property must be an
accessor.
27.1.5 The %AsyncIteratorPrototype% Object
The %AsyncIteratorPrototype% object:
Note
All objects defined in this specification that implement the async iterator interface also
inherit from %AsyncIteratorPrototype%. ECMAScript code may also define objects that
inherit from %AsyncIteratorPrototype%. The %AsyncIteratorPrototype% object provides a
place where additional methods that are applicable to all async iterator objects may be
added.
27.1.5.1 %AsyncIteratorPrototype% [ %Symbol.asyncIterator% ] ( )
This function performs the following steps when called:
Return the this value.
The value of the "name" property of this function is
"[Symbol.asyncIterator]" .
27.1.6 Async-from-Sync Iterator Objects
An Async-from-Sync Iterator
object is an async iterator that adapts a specific
synchronous iterator . Async-from-Sync Iterator objects
are never directly accessible to ECMAScript code. There is not a named constructor for
Async-from-Sync Iterator objects. Instead, Async-from-Sync Iterator objects are created by the
CreateAsyncFromSyncIterator
abstract operation as needed.
27.1.6.1 CreateAsyncFromSyncIterator (
syncIteratorRecord )
The abstract operation CreateAsyncFromSyncIterator takes argument
syncIteratorRecord (an Iterator Record ) and returns an
Iterator Record . It is used to create an
async Iterator Record from a synchronous
Iterator Record . It performs the
following steps when called:
Let asyncIterator be OrdinaryObjectCreate (%AsyncFromSyncIteratorPrototype% ,
« [[SyncIteratorRecord]] »).
Set asyncIterator .[[SyncIteratorRecord]] to
syncIteratorRecord .
Let nextMethod be ! Get (asyncIterator ,
"next" ).
Let iteratorRecord be the Iterator Record {
[[Iterator]] : asyncIterator , [[NextMethod]] : nextMethod , [[Done]] : false }.
Return iteratorRecord .
27.1.6.2 The %AsyncFromSyncIteratorPrototype% Object
The %AsyncFromSyncIteratorPrototype% object:
27.1.6.2.1 %AsyncFromSyncIteratorPrototype%.next ( [
value ] )
Let O be the this value.
Assert : O is an
Object that has a [[SyncIteratorRecord]] internal slot.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let syncIteratorRecord be O .[[SyncIteratorRecord]] .
If value is present, then
Let result be Completion (IteratorNext (syncIteratorRecord ,
value )).
Else,
Let result be Completion (IteratorNext (syncIteratorRecord )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Return AsyncFromSyncIteratorContinuation (result ,
promiseCapability , syncIteratorRecord ,
true ).
27.1.6.2.2 %AsyncFromSyncIteratorPrototype%.return ( [
value ] )
Let O be the this value.
Assert : O is an
Object that has a [[SyncIteratorRecord]] internal slot.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let syncIteratorRecord be O .[[SyncIteratorRecord]] .
Let syncIterator be syncIteratorRecord .[[Iterator]] .
Let return be Completion (GetMethod (syncIterator ,
"return" )).
IfAbruptRejectPromise (return ,
promiseCapability ).
If return is undefined , then
Let iteratorResult be CreateIteratorResultObject (value ,
true ).
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
iteratorResult »).
Return promiseCapability .[[Promise]] .
If value is present, then
Let result be Completion (Call (return ,
syncIterator , « value »)).
Else,
Let result be Completion (Call (return ,
syncIterator )).
IfAbruptRejectPromise (result ,
promiseCapability ).
If result is not an Object , then
Perform ! Call (promiseCapability .[[Reject]] , undefined , « a
newly created TypeError object »).
Return promiseCapability .[[Promise]] .
Return AsyncFromSyncIteratorContinuation (result ,
promiseCapability , syncIteratorRecord ,
false ).
27.1.6.2.3 %AsyncFromSyncIteratorPrototype%.throw ( [
value ] )
Note
In this specification,
value is always provided,
but is left optional for consistency with
%AsyncFromSyncIteratorPrototype%.return
( [ value ] ) .
Let O be the this value.
Assert : O is an
Object that has a [[SyncIteratorRecord]] internal slot.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let syncIteratorRecord be O .[[SyncIteratorRecord]] .
Let syncIterator be syncIteratorRecord .[[Iterator]] .
Let throw be Completion (GetMethod (syncIterator ,
"throw" )).
IfAbruptRejectPromise (throw ,
promiseCapability ).
If throw is undefined , then
NOTE: If syncIterator does not have a throw
method, close it to give it a chance to clean up before we reject the
capability.
Let closeCompletion be NormalCompletion (empty ).
Let result be Completion (IteratorClose (syncIteratorRecord ,
closeCompletion )).
IfAbruptRejectPromise (result ,
promiseCapability ).
NOTE: The next step throws a TypeError to indicate
that there was a protocol violation: syncIterator does not
have a throw method.
NOTE: If closing syncIterator does not throw then the result
of that operation is ignored, even if it yields a rejected promise.
Perform ! Call (promiseCapability .[[Reject]] , undefined , « a
newly created TypeError object »).
Return promiseCapability .[[Promise]] .
If value is present, then
Let result be Completion (Call (throw ,
syncIterator , « value »)).
Else,
Let result be Completion (Call (throw ,
syncIterator )).
IfAbruptRejectPromise (result ,
promiseCapability ).
If result is not an Object , then
Perform ! Call (promiseCapability .[[Reject]] , undefined , « a
newly created TypeError object »).
Return promiseCapability .[[Promise]] .
Return AsyncFromSyncIteratorContinuation (result ,
promiseCapability , syncIteratorRecord ,
true ).
27.1.6.3 Properties of Async-from-Sync Iterator Instances
Async-from-Sync Iterator instances are ordinary
objects that inherit properties from the %AsyncFromSyncIteratorPrototype%
intrinsic object. Async-from-Sync Iterator instances are
initially created with the internal slots listed in Table 89 .
Table 89: Internal Slots of Async-from-Sync Iterator Instances
Internal Slot
Type
Description
[[SyncIteratorRecord]]
an Iterator Record
Represents the original synchronous iterator which is
being adapted.
27.1.6.4 AsyncFromSyncIteratorContinuation ( result ,
promiseCapability , syncIteratorRecord , closeOnRejection )
The abstract operation AsyncFromSyncIteratorContinuation takes arguments result
(an Object), promiseCapability (a PromiseCapability
Record for an intrinsic %Promise% ),
syncIteratorRecord (an Iterator Record ), and
closeOnRejection (a Boolean) and returns a Promise. It performs the following
steps when called:
NOTE: Because promiseCapability is derived from the intrinsic %Promise% , the calls to
promiseCapability .[[Reject]] entailed by the use
IfAbruptRejectPromise below
are guaranteed not to throw.
Let done be Completion (IteratorComplete (result )).
IfAbruptRejectPromise (done ,
promiseCapability ).
Let value be Completion (IteratorValue (result )).
IfAbruptRejectPromise (value ,
promiseCapability ).
Let valueWrapper be Completion (PromiseResolve (%Promise% ,
value )).
If valueWrapper is an abrupt
completion , done is false , and
closeOnRejection is true , then
Set valueWrapper to Completion (IteratorClose (syncIteratorRecord ,
valueWrapper )).
IfAbruptRejectPromise (valueWrapper ,
promiseCapability ).
Let unwrap be a new Abstract Closure
with parameters (v ) that captures done and performs the
following steps when called:
Return CreateIteratorResultObject (v ,
done ).
Let onFulfilled be CreateBuiltinFunction (unwrap ,
1, "" , « »).
NOTE: onFulfilled is used when processing the "value"
property of an IteratorResult object in
order to wait for its value if it is a promise and re-package the result in a new
"unwrapped" IteratorResult object .
If done is true , or if closeOnRejection is
false , then
Let onRejected be undefined .
Else,
Let closeIterator be a new Abstract
Closure with parameters (error ) that
captures syncIteratorRecord and performs the following steps when
called:
Return ? IteratorClose (syncIteratorRecord ,
ThrowCompletion (error )).
Let onRejected be CreateBuiltinFunction (closeIterator ,
1, "" , « »).
NOTE: onRejected is used to close the Iterator when the
"value" property of an IteratorResult
object it yields is a rejected promise.
Perform PerformPromiseThen (valueWrapper ,
onFulfilled , onRejected , promiseCapability ).
Return promiseCapability .[[Promise]] .
27.2 Promise Objects
A Promise is an object that is used as a placeholder for the eventual results of a deferred (and
possibly asynchronous) computation.
Any Promise is in one of three mutually exclusive states: fulfilled , rejected , and
pending :
A promise p is fulfilled if p.then(f, r) will immediately enqueue a
Job to call the function
f.
A promise p is rejected if p.then(f, r) will immediately enqueue a
Job to call the function
r.
A promise is pending if it is neither fulfilled nor rejected.
A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or
rejected.
A promise is resolved if it is settled or if it has been “locked in” to match the state of
another promise. Attempting to resolve or reject a resolved promise has no effect. A promise is
unresolved if it is not resolved. An unresolved promise is always in the pending state. A
resolved promise may be pending, fulfilled or rejected.
27.2.1 Promise Abstract Operations
27.2.1.1 PromiseCapability Records
A PromiseCapability Record is a
Record value used to
encapsulate a Promise or promise-like object along with the functions that are capable of
resolving or rejecting that promise. PromiseCapability Records are produced by the NewPromiseCapability abstract
operation.
PromiseCapability Records have the fields listed in Table 90 .
Table 90: PromiseCapability
Record Fields
Field Name
Value
Meaning
[[Promise]]
an Object
An object that is usable as a promise.
[[Resolve]]
a function object
The function that is used to resolve the given promise.
[[Reject]]
a function object
The function that is used to reject the given promise.
27.2.1.1.1 IfAbruptRejectPromise ( value ,
capability )
IfAbruptRejectPromise is a shorthand for a sequence of algorithm steps that use a
PromiseCapability Record .
An algorithm step of the form:
IfAbruptRejectPromise (value ,
capability ).
means the same thing as:
Assert : value is a Completion
Record .
If value is an abrupt
completion , then
Perform ? Call (capability .[[Reject]] , undefined , «
value .[[Value]] »).
Return capability .[[Promise]] .
Else,
Set value to ! value .
27.2.1.2 PromiseReaction Records
A PromiseReaction Record is a
Record value used to
store information about how a promise should react when it becomes resolved or rejected with
a given value. PromiseReaction Records are created by the PerformPromiseThen abstract operation,
and are used by the Abstract Closure returned by NewPromiseReactionJob .
PromiseReaction Records have the fields listed in Table 91 .
Table 91: PromiseReaction Record
Fields
Field Name
Value
Meaning
[[Capability]]
a PromiseCapability
Record or undefined
The capabilities of the promise for which this record provides a
reaction handler.
[[Type]]
fulfill or reject
The [[Type]] is used when [[Handler]] is empty to
allow for behaviour specific to the settlement type.
[[Handler]]
a JobCallback
Record or empty
The function that should be applied to the incoming value, and whose
return value will govern what happens to the derived promise. If [[Handler]] is empty , a
function that depends on the value of [[Type]]
will be used instead.
27.2.1.3 CreateResolvingFunctions ( promise )
The abstract operation CreateResolvingFunctions takes argument promise (a Promise)
and returns a Record with fields
[[Resolve]] (a function object ) and [[Reject]] (a function object ). It performs the following
steps when called:
Let alreadyResolved be the Record { [[Value]] : false }.
Let stepsResolve be the algorithm steps defined in Promise Resolve
Functions .
Let lengthResolve be the number of non-optional parameters of the
function definition in Promise Resolve
Functions .
Let resolve be CreateBuiltinFunction (stepsResolve ,
lengthResolve , "" , « [[Promise]] , [[AlreadyResolved]] »).
Set resolve .[[Promise]] to promise .
Set resolve .[[AlreadyResolved]] to
alreadyResolved .
Let stepsReject be the algorithm steps defined in Promise Reject
Functions .
Let lengthReject be the number of non-optional parameters of the function
definition in Promise Reject
Functions .
Let reject be CreateBuiltinFunction (stepsReject ,
lengthReject , "" , « [[Promise]] , [[AlreadyResolved]] »).
Set reject .[[Promise]] to promise .
Set reject .[[AlreadyResolved]] to
alreadyResolved .
Return the Record { [[Resolve]] : resolve , [[Reject]] : reject }.
27.2.1.3.1 Promise Reject Functions
A promise reject function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]]
internal slots.
When a promise reject function is called with argument reason , the following
steps are taken:
Let F be the active function
object .
Assert : F has a [[Promise]] internal slot whose value is an
Object .
Let promise be F .[[Promise]] .
Let alreadyResolved be F .[[AlreadyResolved]] .
If alreadyResolved .[[Value]] is
true , return undefined .
Set alreadyResolved .[[Value]] to
true .
Perform RejectPromise (promise ,
reason ).
Return undefined .
The "length" property of a promise reject function is
1 𝔽 .
27.2.1.3.2 Promise Resolve Functions
A promise resolve function is an anonymous built-in function that has [[Promise]] and [[AlreadyResolved]]
internal slots.
When a promise resolve function is called with argument resolution , the
following steps are taken:
Let F be the active function
object .
Assert : F has a [[Promise]] internal slot whose value is an
Object .
Let promise be F .[[Promise]] .
Let alreadyResolved be F .[[AlreadyResolved]] .
If alreadyResolved .[[Value]] is
true , return undefined .
Set alreadyResolved .[[Value]] to
true .
If SameValue (resolution ,
promise ) is true , then
Let selfResolutionError be a newly created
TypeError object.
Perform RejectPromise (promise ,
selfResolutionError ).
Return undefined .
If resolution is not an Object , then
Perform FulfillPromise (promise ,
resolution ).
Return undefined .
Let then be Completion (Get (resolution ,
"then" )).
If then is an abrupt
completion , then
Perform RejectPromise (promise ,
then .[[Value]] ).
Return undefined .
Let thenAction be then .[[Value]] .
If IsCallable (thenAction )
is false , then
Perform FulfillPromise (promise ,
resolution ).
Return undefined .
Let thenJobCallback be HostMakeJobCallback (thenAction ).
Let job be NewPromiseResolveThenableJob (promise ,
resolution , thenJobCallback ).
Perform HostEnqueuePromiseJob (job .[[Job]] , job .[[Realm]] ).
Return undefined .
The "length" property of a promise resolve function is
1 𝔽 .
27.2.1.4 FulfillPromise ( promise , value )
The abstract operation FulfillPromise takes arguments promise (a Promise) and
value (an ECMAScript language value ) and
returns unused . It performs the following steps when called:
Assert :
promise .[[PromiseState]] is
pending .
Let reactions be promise .[[PromiseFulfillReactions]] .
Set promise .[[PromiseResult]] to
value .
Set promise .[[PromiseFulfillReactions]] to
undefined .
Set promise .[[PromiseRejectReactions]] to
undefined .
Set promise .[[PromiseState]] to
fulfilled .
Perform TriggerPromiseReactions (reactions ,
value ).
Return unused .
27.2.1.5 NewPromiseCapability ( C )
The abstract operation NewPromiseCapability takes argument C (an ECMAScript language value ) and
returns either a normal completion
containing a PromiseCapability
Record or a throw completion . It
attempts to use C as a constructor in the fashion of the built-in
Promise constructor to create a promise and extract its
resolve and reject functions. The promise plus the
resolve and reject functions are used to initialize a new
PromiseCapability Record . It
performs the following steps when called:
If IsConstructor (C ) is
false , throw a TypeError exception.
NOTE: C is assumed to be a constructor function that
supports the parameter conventions of the Promise constructor (see 27.2.3.1 ).
Let resolvingFunctions be the Record { [[Resolve]] : undefined , [[Reject]] : undefined }.
Let executorClosure be a new Abstract Closure
with parameters (resolve , reject ) that captures
resolvingFunctions and performs the following steps when called:
If resolvingFunctions .[[Resolve]] is not
undefined , throw a TypeError
exception.
If resolvingFunctions .[[Reject]] is not
undefined , throw a TypeError
exception.
Set resolvingFunctions .[[Resolve]] to
resolve .
Set resolvingFunctions .[[Reject]] to
reject .
Return NormalCompletion (undefined ).
Let executor be CreateBuiltinFunction (executorClosure ,
2, "" , « »).
Let promise be ? Construct (C , «
executor »).
If IsCallable (resolvingFunctions .[[Resolve]] ) is false , throw a
TypeError exception.
If IsCallable (resolvingFunctions .[[Reject]] ) is false , throw a
TypeError exception.
Return the PromiseCapability
Record { [[Promise]] :
promise , [[Resolve]] :
resolvingFunctions .[[Resolve]] , [[Reject]] : resolvingFunctions .[[Reject]] }.
Note
This abstract operation supports Promise subclassing, as it is generic on any
constructor that calls a passed executor
function argument in the same way as the Promise constructor . It is used to
generalize static methods of the Promise constructor to any
subclass.
27.2.1.6 IsPromise ( x )
The abstract operation IsPromise takes argument x (an ECMAScript language value ) and
returns a Boolean. It checks for the promise brand on an object. It performs the following
steps when called:
If x is not an Object , return
false .
If x does not have a [[PromiseState]] internal
slot, return false .
Return true .
27.2.1.7 RejectPromise ( promise , reason )
The abstract operation RejectPromise takes arguments promise (a Promise) and
reason (an ECMAScript language value ) and
returns unused . It performs the following steps when called:
Assert :
promise .[[PromiseState]] is
pending .
Let reactions be promise .[[PromiseRejectReactions]] .
Set promise .[[PromiseResult]] to
reason .
Set promise .[[PromiseFulfillReactions]] to
undefined .
Set promise .[[PromiseRejectReactions]] to
undefined .
Set promise .[[PromiseState]] to
rejected .
If promise .[[PromiseIsHandled]] is
false , perform HostPromiseRejectionTracker (promise ,
"reject" ).
Perform TriggerPromiseReactions (reactions ,
reason ).
Return unused .
27.2.1.8 TriggerPromiseReactions ( reactions ,
argument )
The abstract operation TriggerPromiseReactions takes arguments reactions (a
List of PromiseReaction Records ) and
argument (an ECMAScript language value ) and
returns unused . It enqueues a new Job for each record in
reactions . Each such Job processes the [[Type]] and
[[Handler]] of the PromiseReaction
Record , and if the [[Handler]] is not
empty , calls it passing the given argument. If the [[Handler]] is empty , the behaviour is
determined by the [[Type]] . It performs the following steps when
called:
For each element reaction of reactions , do
Let job be NewPromiseReactionJob (reaction ,
argument ).
Perform HostEnqueuePromiseJob (job .[[Job]] , job .[[Realm]] ).
Return unused .
27.2.1.9 HostPromiseRejectionTracker ( promise ,
operation )
The host-defined abstract operation
HostPromiseRejectionTracker takes arguments promise (a Promise) and
operation ("reject" or "handle" ) and
returns unused . It allows host environments to track
promise rejections.
The default implementation of HostPromiseRejectionTracker is to return
unused .
Note 1
HostPromiseRejectionTracker is called in two scenarios:
When a promise is rejected without any handlers, it is called with its
operation argument set to "reject" .
When a handler is added to a rejected promise for the first time, it is called
with its operation argument set to "handle" .
A typical implementation of HostPromiseRejectionTracker might try to notify
developers of unhandled rejections, while also being careful to notify them if such
previous notifications are later invalidated by new handlers being attached.
Note 2
If operation is "handle" , an implementation should not
hold a reference to promise in a way that would interfere with garbage
collection. An implementation may hold a reference to promise if
operation is "reject" , since it is expected that
rejections will be rare and not on hot code paths.
27.2.2 Promise Jobs
27.2.2.1 NewPromiseReactionJob ( reaction ,
argument )
The abstract operation NewPromiseReactionJob takes arguments reaction (a PromiseReaction Record ) and
argument (an ECMAScript language value ) and
returns a Record with fields
[[Job]] (a Job Abstract Closure ) and
[[Realm]] (a Realm Record or null ). It
returns a new Job
Abstract Closure that applies the
appropriate handler to the incoming value, and uses the handler's return value to resolve or
reject the derived promise associated with that handler. It performs the following steps
when called:
Let job be a new Job Abstract Closure
with no parameters that captures reaction and argument and
performs the following steps when called:
Let promiseCapability be reaction .[[Capability]] .
Let type be reaction .[[Type]] .
Let handler be reaction .[[Handler]] .
If handler is empty , then
If type is fulfill , then
Let handlerResult be NormalCompletion (argument ).
Else,
Assert :
type is reject .
Let handlerResult be ThrowCompletion (argument ).
Else,
Let handlerResult be Completion (HostCallJobCallback (handler ,
undefined , « argument »)).
If promiseCapability is undefined , then
Assert :
handlerResult is not an abrupt
completion .
Return empty .
Assert : promiseCapability
is a PromiseCapability
Record .
If handlerResult is an abrupt
completion , then
Return ? Call (promiseCapability .[[Reject]] , undefined , «
handlerResult .[[Value]] »).
Else,
Return ? Call (promiseCapability .[[Resolve]] , undefined , «
handlerResult .[[Value]] »).
Let handlerRealm be null .
If reaction .[[Handler]] is not
empty , then
Let getHandlerRealmResult be Completion (GetFunctionRealm (reaction .[[Handler]] .[[Callback]] )).
If getHandlerRealmResult is a normal
completion , set handlerRealm to
getHandlerRealmResult .[[Value]] .
Else, set handlerRealm to the current Realm
Record .
NOTE: handlerRealm is never null unless the
handler is undefined . When the handler is a revoked Proxy
and no ECMAScript code runs, handlerRealm is used to create error
objects.
Return the Record { [[Job]] : job , [[Realm]] :
handlerRealm }.
27.2.2.2 NewPromiseResolveThenableJob (
promiseToResolve , thenable , then )
The abstract operation NewPromiseResolveThenableJob takes arguments
promiseToResolve (a Promise), thenable (an Object), and
then (a JobCallback Record ) and returns a
Record with fields
[[Job]] (a Job Abstract Closure ) and
[[Realm]] (a Realm Record ). It performs the following steps
when called:
Let job be a new Job Abstract Closure
with no parameters that captures promiseToResolve , thenable ,
and then and performs the following steps when called:
Let resolvingFunctions be CreateResolvingFunctions (promiseToResolve ).
Let thenCallResult be Completion (HostCallJobCallback (then ,
thenable , « resolvingFunctions .[[Resolve]] , resolvingFunctions .[[Reject]] »)).
If thenCallResult is an abrupt
completion , then
Return ? Call (resolvingFunctions .[[Reject]] , undefined , «
thenCallResult .[[Value]] »).
Return ! thenCallResult .
Let getThenRealmResult be Completion (GetFunctionRealm (then .[[Callback]] )).
If getThenRealmResult is a normal
completion , let thenRealm be
getThenRealmResult .[[Value]] .
Else, let thenRealm be the current Realm Record .
NOTE: thenRealm is never null . When
then .[[Callback]] is a revoked Proxy and no code
runs, thenRealm is used to create error objects.
Return the Record { [[Job]] : job , [[Realm]] :
thenRealm }.
Note
This Job uses the
supplied thenable and its then method to resolve the given promise.
This process must take place as a Job to ensure that the evaluation of the
then method occurs after evaluation of any surrounding code has
completed.
27.2.3 The Promise Constructor
The Promise constructor :
is %Promise% .
is the initial value of the "Promise" property of the global
object .
creates and initializes a new Promise when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
may be used as the value in an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
Promise behaviour must include a super call to the Promise constructor to
create and initialize the subclass instance with the internal state necessary to support the
Promise and Promise.prototype built-in methods.
27.2.3.1 Promise ( executor )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
If IsCallable (executor ) is
false , throw a TypeError exception.
Let promise be ? OrdinaryCreateFromConstructor (NewTarget,
"%Promise.prototype%" , « [[PromiseState]] , [[PromiseResult]] , [[PromiseFulfillReactions]] , [[PromiseRejectReactions]] , [[PromiseIsHandled]] »).
Set promise .[[PromiseState]] to
pending .
Set promise .[[PromiseResult]] to
empty .
Set promise .[[PromiseFulfillReactions]] to a new
empty List .
Set promise .[[PromiseRejectReactions]] to a new
empty List .
Set promise .[[PromiseIsHandled]] to
false .
Let resolvingFunctions be CreateResolvingFunctions (promise ).
Let completion be Completion (Call (executor ,
undefined , « resolvingFunctions .[[Resolve]] , resolvingFunctions .[[Reject]] »)).
If completion is an abrupt
completion , then
Perform ? Call (resolvingFunctions .[[Reject]] , undefined , «
completion .[[Value]] »).
Return promise .
Note
The executor argument must be a function object . It is
called for initiating and reporting completion of the possibly deferred action
represented by this Promise. The executor is called with two arguments:
resolve and reject . These are functions that may be used by
the executor function to report eventual completion or failure of the
deferred computation. Returning from the executor function does not mean that the
deferred action has been completed but only that the request to eventually perform
the deferred action has been accepted.
The resolve function that is passed to an executor function
accepts a single argument. The executor code may eventually call the
resolve function to indicate that it wishes to resolve the associated
Promise. The argument passed to the resolve function represents the
eventual value of the deferred action and can be either the actual fulfillment value
or another promise which will provide the value if it is fulfilled.
The reject function that is passed to an executor function
accepts a single argument. The executor code may eventually call the
reject function to indicate that the associated Promise is rejected and
will never be fulfilled. The argument passed to the reject function is
used as the rejection value of the promise. Typically it will be an Error object.
The resolve and reject functions passed to an executor function by the
Promise constructor have the capability to
actually resolve and reject the associated promise. Subclasses may have different
constructor behaviour that passes in
customized values for resolve and reject.
27.2.4 Properties of the Promise Constructor
The Promise constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
has the following properties:
27.2.4.1 Promise.all ( iterable )
This function returns a new promise which is fulfilled with an array of fulfillment values
for the passed promises, or rejects with the reason of the first passed promise that
rejects. It resolves all elements of the passed iterable to promises as
it runs this algorithm.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Let promiseResolve be Completion (GetPromiseResolve (C )).
IfAbruptRejectPromise (promiseResolve ,
promiseCapability ).
Let iteratorRecord be Completion (GetIterator (iterable ,
sync )).
IfAbruptRejectPromise (iteratorRecord ,
promiseCapability ).
Let result be Completion (PerformPromiseAll (iteratorRecord ,
C , promiseCapability , promiseResolve )).
If result is an abrupt
completion , then
If iteratorRecord .[[Done]] is
false , set result to Completion (IteratorClose (iteratorRecord ,
result )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Return ! result .
Note
This function requires its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.1.1 GetPromiseResolve ( promiseConstructor
)
The abstract operation GetPromiseResolve takes argument promiseConstructor (a
constructor ) and returns either a normal completion
containing a function object or a throw
completion . It performs the following steps when called:
Let promiseResolve be ? Get (promiseConstructor ,
"resolve" ).
If IsCallable (promiseResolve )
is false , throw a TypeError exception.
Return promiseResolve .
27.2.4.1.2 PerformPromiseAll ( iteratorRecord ,
constructor , resultCapability , promiseResolve )
The abstract operation PerformPromiseAll takes arguments iteratorRecord (an
Iterator Record ),
constructor (a constructor ), resultCapability (a
PromiseCapability Record ),
and promiseResolve (a function object ) and returns either a
normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Let values be a new empty List .
Let remainingElementsCount be the Record {
[[Value]] : 1 }.
Let index be 0.
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , then
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0, then
Let valuesArray be CreateArrayFromList (values ).
Perform ? Call (resultCapability .[[Resolve]] ,
undefined , «
valuesArray »).
Return resultCapability .[[Promise]] .
Append undefined to values .
Let nextPromise be ? Call (promiseResolve ,
constructor , « next »).
Let steps be the algorithm steps defined in Promise.all
Resolve Element Functions .
Let length be the number of non-optional parameters of the
function definition in Promise.all
Resolve Element Functions .
Let onFulfilled be CreateBuiltinFunction (steps ,
length , "" , « [[AlreadyCalled]] , [[Index]] , [[Values]] ,
[[Capability]] , [[RemainingElements]] »).
Set onFulfilled .[[AlreadyCalled]] to
false .
Set onFulfilled .[[Index]] to
index .
Set onFulfilled .[[Values]] to
values .
Set onFulfilled .[[Capability]] to
resultCapability .
Set onFulfilled .[[RemainingElements]] to
remainingElementsCount .
Set remainingElementsCount .[[Value]]
to remainingElementsCount .[[Value]]
+ 1.
Perform ? Invoke (nextPromise ,
"then" , « onFulfilled ,
resultCapability .[[Reject]] »).
Set index to index + 1.
27.2.4.1.3 Promise.all Resolve Element
Functions
A Promise.all resolve element function is an anonymous built-in function
that is used to resolve a specific Promise.all element. Each
Promise.all resolve element function has [[Index]] , [[Values]] , [[Capability]] , [[RemainingElements]] ,
and [[AlreadyCalled]] internal slots.
When a Promise.all resolve element function is called with argument
x , the following steps are taken:
Let F be the active function
object .
If F .[[AlreadyCalled]] is
true , return undefined .
Set F .[[AlreadyCalled]] to
true .
Let index be F .[[Index]] .
Let values be F .[[Values]] .
Let promiseCapability be F .[[Capability]] .
Let remainingElementsCount be F .[[RemainingElements]] .
Set values [index ] to x .
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0,
then
Let valuesArray be CreateArrayFromList (values ).
Return ? Call (promiseCapability .[[Resolve]] , undefined , «
valuesArray »).
Return undefined .
The "length" property of a Promise.all resolve element
function is 1 𝔽 .
27.2.4.2 Promise.allSettled ( iterable )
This function returns a promise that is fulfilled with an array of promise state snapshots,
but only after all the original promises have settled, i.e. become either fulfilled or
rejected. It resolves all elements of the passed iterable to promises as
it runs this algorithm.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Let promiseResolve be Completion (GetPromiseResolve (C )).
IfAbruptRejectPromise (promiseResolve ,
promiseCapability ).
Let iteratorRecord be Completion (GetIterator (iterable ,
sync )).
IfAbruptRejectPromise (iteratorRecord ,
promiseCapability ).
Let result be Completion (PerformPromiseAllSettled (iteratorRecord ,
C , promiseCapability , promiseResolve )).
If result is an abrupt
completion , then
If iteratorRecord .[[Done]] is
false , set result to Completion (IteratorClose (iteratorRecord ,
result )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Return ! result .
Note
This function requires its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.2.1 PerformPromiseAllSettled (
iteratorRecord , constructor , resultCapability ,
promiseResolve )
The abstract operation PerformPromiseAllSettled takes arguments iteratorRecord
(an Iterator Record ),
constructor (a constructor ), resultCapability (a
PromiseCapability Record ),
and promiseResolve (a function object ) and returns either a
normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Let values be a new empty List .
Let remainingElementsCount be the Record {
[[Value]] : 1 }.
Let index be 0.
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , then
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0, then
Let valuesArray be CreateArrayFromList (values ).
Perform ? Call (resultCapability .[[Resolve]] ,
undefined , «
valuesArray »).
Return resultCapability .[[Promise]] .
Append undefined to values .
Let nextPromise be ? Call (promiseResolve ,
constructor , « next »).
Let stepsFulfilled be the algorithm steps defined in
Promise.allSettled
Resolve Element Functions .
Let lengthFulfilled be the number of non-optional parameters
of the function definition in Promise.allSettled
Resolve Element Functions .
Let onFulfilled be CreateBuiltinFunction (stepsFulfilled ,
lengthFulfilled , "" , « [[AlreadyCalled]] , [[Index]] , [[Values]] ,
[[Capability]] , [[RemainingElements]] »).
Let alreadyCalled be the Record
{ [[Value]] : false }.
Set onFulfilled .[[AlreadyCalled]] to
alreadyCalled .
Set onFulfilled .[[Index]] to
index .
Set onFulfilled .[[Values]] to
values .
Set onFulfilled .[[Capability]] to
resultCapability .
Set onFulfilled .[[RemainingElements]] to
remainingElementsCount .
Let stepsRejected be the algorithm steps defined in Promise.allSettled
Reject Element Functions .
Let lengthRejected be the number of non-optional parameters
of the function definition in Promise.allSettled
Reject Element Functions .
Let onRejected be CreateBuiltinFunction (stepsRejected ,
lengthRejected , "" , « [[AlreadyCalled]] , [[Index]] , [[Values]] ,
[[Capability]] , [[RemainingElements]] »).
Set onRejected .[[AlreadyCalled]] to
alreadyCalled .
Set onRejected .[[Index]] to
index .
Set onRejected .[[Values]] to
values .
Set onRejected .[[Capability]] to
resultCapability .
Set onRejected .[[RemainingElements]]
to remainingElementsCount .
Set remainingElementsCount .[[Value]]
to remainingElementsCount .[[Value]]
+ 1.
Perform ? Invoke (nextPromise ,
"then" , « onFulfilled ,
onRejected »).
Set index to index + 1.
27.2.4.2.2 Promise.allSettled Resolve Element
Functions
A Promise.allSettled resolve element function is an anonymous built-in
function that is used to resolve a specific Promise.allSettled element.
Each Promise.allSettled resolve element function has [[Index]] , [[Values]] , [[Capability]] , [[RemainingElements]] ,
and [[AlreadyCalled]] internal slots.
When a Promise.allSettled resolve element function is called with argument
x , the following steps are taken:
Let F be the active function
object .
Let alreadyCalled be F .[[AlreadyCalled]] .
If alreadyCalled .[[Value]] is
true , return undefined .
Set alreadyCalled .[[Value]] to
true .
Let index be F .[[Index]] .
Let values be F .[[Values]] .
Let promiseCapability be F .[[Capability]] .
Let remainingElementsCount be F .[[RemainingElements]] .
Let obj be OrdinaryObjectCreate (%Object.prototype% ).
Perform ! CreateDataPropertyOrThrow (obj ,
"status" , "fulfilled" ).
Perform ! CreateDataPropertyOrThrow (obj ,
"value" , x ).
Set values [index ] to obj .
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0,
then
Let valuesArray be CreateArrayFromList (values ).
Return ? Call (promiseCapability .[[Resolve]] , undefined , «
valuesArray »).
Return undefined .
The "length" property of a Promise.allSettled resolve
element function is 1 𝔽 .
27.2.4.2.3 Promise.allSettled Reject Element
Functions
A Promise.allSettled reject element function is an anonymous built-in
function that is used to reject a specific Promise.allSettled element. Each
Promise.allSettled reject element function has [[Index]] , [[Values]] , [[Capability]] , [[RemainingElements]] ,
and [[AlreadyCalled]] internal slots.
When a Promise.allSettled reject element function is called with argument
x , the following steps are taken:
Let F be the active function
object .
Let alreadyCalled be F .[[AlreadyCalled]] .
If alreadyCalled .[[Value]] is
true , return undefined .
Set alreadyCalled .[[Value]] to
true .
Let index be F .[[Index]] .
Let values be F .[[Values]] .
Let promiseCapability be F .[[Capability]] .
Let remainingElementsCount be F .[[RemainingElements]] .
Let obj be OrdinaryObjectCreate (%Object.prototype% ).
Perform ! CreateDataPropertyOrThrow (obj ,
"status" , "rejected" ).
Perform ! CreateDataPropertyOrThrow (obj ,
"reason" , x ).
Set values [index ] to obj .
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0,
then
Let valuesArray be CreateArrayFromList (values ).
Return ? Call (promiseCapability .[[Resolve]] , undefined , «
valuesArray »).
Return undefined .
The "length" property of a Promise.allSettled reject
element function is 1 𝔽 .
27.2.4.3 Promise.any ( iterable )
This function returns a promise that is fulfilled by the first given promise to be fulfilled,
or rejected with an AggregateError holding the rejection reasons if all of the
given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this
algorithm.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Let promiseResolve be Completion (GetPromiseResolve (C )).
IfAbruptRejectPromise (promiseResolve ,
promiseCapability ).
Let iteratorRecord be Completion (GetIterator (iterable ,
sync )).
IfAbruptRejectPromise (iteratorRecord ,
promiseCapability ).
Let result be Completion (PerformPromiseAny (iteratorRecord ,
C , promiseCapability , promiseResolve )).
If result is an abrupt
completion , then
If iteratorRecord .[[Done]] is
false , set result to Completion (IteratorClose (iteratorRecord ,
result )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Return ! result .
Note
This function requires its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.3.1 PerformPromiseAny ( iteratorRecord ,
constructor , resultCapability , promiseResolve )
The abstract operation PerformPromiseAny takes arguments iteratorRecord (an
Iterator Record ),
constructor (a constructor ), resultCapability (a
PromiseCapability Record ),
and promiseResolve (a function object ) and returns either a
normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Let errors be a new empty List .
Let remainingElementsCount be the Record {
[[Value]] : 1 }.
Let index be 0.
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , then
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0, then
Let error be a newly created
AggregateError object.
Perform ! DefinePropertyOrThrow (error ,
"errors" , PropertyDescriptor { [[Configurable]] :
true , [[Enumerable]] :
false , [[Writable]] :
true , [[Value]] : CreateArrayFromList (errors ) }).
Return ThrowCompletion (error ).
Return resultCapability .[[Promise]] .
Append undefined to errors .
Let nextPromise be ? Call (promiseResolve ,
constructor , « next »).
Let stepsRejected be the algorithm steps defined in Promise.any
Reject Element Functions .
Let lengthRejected be the number of non-optional parameters
of the function definition in Promise.any
Reject Element Functions .
Let onRejected be CreateBuiltinFunction (stepsRejected ,
lengthRejected , "" , « [[AlreadyCalled]] , [[Index]] , [[Errors]] ,
[[Capability]] , [[RemainingElements]] »).
Set onRejected .[[AlreadyCalled]] to
false .
Set onRejected .[[Index]] to
index .
Set onRejected .[[Errors]] to
errors .
Set onRejected .[[Capability]] to
resultCapability .
Set onRejected .[[RemainingElements]]
to remainingElementsCount .
Set remainingElementsCount .[[Value]]
to remainingElementsCount .[[Value]]
+ 1.
Perform ? Invoke (nextPromise ,
"then" , « resultCapability .[[Resolve]] , onRejected »).
Set index to index + 1.
27.2.4.3.2 Promise.any Reject Element Functions
A Promise.any reject element function is an anonymous built-in function that
is used to reject a specific Promise.any element. Each
Promise.any reject element function has [[Index]] ,
[[Errors]] , [[Capability]] , [[RemainingElements]] , and [[AlreadyCalled]] internal slots.
When a Promise.any reject element function is called with argument
x , the following steps are taken:
Let F be the active function
object .
If F .[[AlreadyCalled]] is
true , return undefined .
Set F .[[AlreadyCalled]] to
true .
Let index be F .[[Index]] .
Let errors be F .[[Errors]] .
Let promiseCapability be F .[[Capability]] .
Let remainingElementsCount be F .[[RemainingElements]] .
Set errors [index ] to x .
Set remainingElementsCount .[[Value]] to
remainingElementsCount .[[Value]] - 1.
If remainingElementsCount .[[Value]] = 0,
then
Let error be a newly created
AggregateError object.
Perform ! DefinePropertyOrThrow (error ,
"errors" , PropertyDescriptor { [[Configurable]] : true , [[Enumerable]] : false , [[Writable]] : true , [[Value]] : CreateArrayFromList (errors ) }).
Return ? Call (promiseCapability .[[Reject]] , undefined , «
error »).
Return undefined .
The "length" property of a Promise.any reject element
function is 1 𝔽 .
27.2.4.4 Promise.prototype
The initial value of Promise.prototype is the Promise prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
27.2.4.5 Promise.race ( iterable )
This function returns a new promise which is settled in the same way as the first passed
promise to settle. It resolves all elements of the passed iterable to promises as
it runs this algorithm.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Let promiseResolve be Completion (GetPromiseResolve (C )).
IfAbruptRejectPromise (promiseResolve ,
promiseCapability ).
Let iteratorRecord be Completion (GetIterator (iterable ,
sync )).
IfAbruptRejectPromise (iteratorRecord ,
promiseCapability ).
Let result be Completion (PerformPromiseRace (iteratorRecord ,
C , promiseCapability , promiseResolve )).
If result is an abrupt
completion , then
If iteratorRecord .[[Done]] is
false , set result to Completion (IteratorClose (iteratorRecord ,
result )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Return ! result .
Note 1
If the iterable argument yields no values or if none of the promises
yielded by iterable ever settle, then the pending promise returned by
this method will never be settled.
Note 2
This function expects its this value to be a constructor function that supports the
parameter conventions of the Promise constructor . It also
expects that its this value provides a resolve
method.
27.2.4.5.1 PerformPromiseRace ( iteratorRecord ,
constructor , resultCapability , promiseResolve )
The abstract operation PerformPromiseRace takes arguments iteratorRecord (an
Iterator Record ),
constructor (a constructor ), resultCapability (a
PromiseCapability Record ),
and promiseResolve (a function object ) and returns either a
normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Repeat,
Let next be ? IteratorStepValue (iteratorRecord ).
If next is done , then
Return resultCapability .[[Promise]] .
Let nextPromise be ? Call (promiseResolve ,
constructor , « next »).
Perform ? Invoke (nextPromise ,
"then" , « resultCapability .[[Resolve]] , resultCapability .[[Reject]] »).
27.2.4.6 Promise.reject ( r )
This function returns a new promise rejected with the passed argument.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Perform ? Call (promiseCapability .[[Reject]] , undefined , «
r »).
Return promiseCapability .[[Promise]] .
Note
This function expects its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.7 Promise.resolve ( x )
This function returns either a new promise resolved with the passed argument, or the argument
itself if the argument is a promise produced by this constructor .
Let C be the this value.
If C is not an Object , throw a
TypeError exception.
Return ? PromiseResolve (C ,
x ).
Note
This function expects its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.7.1 PromiseResolve ( C , x )
The abstract operation PromiseResolve takes arguments C (an Object) and
x (an ECMAScript language value )
and returns either a normal
completion containing an ECMAScript language value
or a throw
completion . It returns a new promise resolved with x .
It performs the following steps when called:
If IsPromise (x ) is
true , then
Let xConstructor be ? Get (x ,
"constructor" ).
If SameValue (xConstructor ,
C ) is true , return x .
Let promiseCapability be ? NewPromiseCapability (C ).
Perform ? Call (promiseCapability .[[Resolve]] , undefined , «
x »).
Return promiseCapability .[[Promise]] .
27.2.4.8 Promise.try ( callback , ...args )
This function performs the following steps when called:
Let C be the this value.
If C is not an Object , throw a
TypeError exception.
Let promiseCapability be ? NewPromiseCapability (C ).
Let status be Completion (Call (callback ,
undefined , args )).
If status is an abrupt
completion , then
Perform ? Call (promiseCapability .[[Reject]] , undefined , «
status .[[Value]] »).
Else,
Perform ? Call (promiseCapability .[[Resolve]] , undefined , «
status .[[Value]] »).
Return promiseCapability .[[Promise]] .
Note
This function expects its this value to be a constructor function that supports the
parameter conventions of the Promise constructor .
27.2.4.9 Promise.withResolvers ( )
This function returns an object with three properties: a new promise together with the
resolve and reject functions associated with it.
Let C be the this value.
Let promiseCapability be ? NewPromiseCapability (C ).
Let obj be OrdinaryObjectCreate (%Object.prototype% ).
Perform ! CreateDataPropertyOrThrow (obj ,
"promise" , promiseCapability .[[Promise]] ).
Perform ! CreateDataPropertyOrThrow (obj ,
"resolve" , promiseCapability .[[Resolve]] ).
Perform ! CreateDataPropertyOrThrow (obj ,
"reject" , promiseCapability .[[Reject]] ).
Return obj .
27.2.4.10 get Promise [ %Symbol.species% ]
Promise[%Symbol.species%] is an accessor property whose set
accessor function is undefined . Its get accessor function performs the
following steps when called:
Return the this value.
The value of the "name" property of this function is "get
[Symbol.species]" .
Note
Promise prototype methods normally use their this value's
constructor to create a derived object.
However, a subclass constructor may over-ride that default
behaviour by redefining its %Symbol.species% property.
27.2.5 Properties of the Promise Prototype Object
The Promise prototype object :
is %Promise.prototype% .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is an ordinary
object .
does not have a [[PromiseState]] internal slot or any of the other
internal slots of Promise instances.
27.2.5.1 Promise.prototype.catch ( onRejected )
This method performs the following steps when called:
Let promise be the this value.
Return ? Invoke (promise ,
"then" , « undefined ,
onRejected »).
27.2.5.2 Promise.prototype.constructor
The initial value of Promise.prototype.constructor is %Promise% .
27.2.5.3 Promise.prototype.finally ( onFinally )
This method performs the following steps when called:
Let promise be the this value.
If promise is not an Object , throw a
TypeError exception.
Let C be ? SpeciesConstructor (promise ,
%Promise% ).
Assert :
IsConstructor (C ) is
true .
If IsCallable (onFinally ) is
false , then
Let thenFinally be onFinally .
Let catchFinally be onFinally .
Else,
Let thenFinallyClosure be a new Abstract Closure with
parameters (value ) that captures onFinally and
C and performs the following steps when called:
Let result be ? Call (onFinally ,
undefined ).
Let p be ? PromiseResolve (C ,
result ).
Let returnValue be a new Abstract Closure
with no parameters that captures value and performs the
following steps when called:
Return NormalCompletion (value ).
Let valueThunk be CreateBuiltinFunction (returnValue ,
0, "" , « »).
Return ? Invoke (p ,
"then" , « valueThunk »).
Let thenFinally be CreateBuiltinFunction (thenFinallyClosure ,
1, "" , « »).
Let catchFinallyClosure be a new Abstract Closure with
parameters (reason ) that captures onFinally and
C and performs the following steps when called:
Let result be ? Call (onFinally ,
undefined ).
Let p be ? PromiseResolve (C ,
result ).
Let throwReason be a new Abstract Closure
with no parameters that captures reason and performs the
following steps when called:
Return ThrowCompletion (reason ).
Let thrower be CreateBuiltinFunction (throwReason ,
0, "" , « »).
Return ? Invoke (p ,
"then" , « thrower »).
Let catchFinally be CreateBuiltinFunction (catchFinallyClosure ,
1, "" , « »).
Return ? Invoke (promise ,
"then" , « thenFinally ,
catchFinally »).
27.2.5.4 Promise.prototype.then ( onFulfilled ,
onRejected )
This method performs the following steps when called:
Let promise be the this value.
If IsPromise (promise ) is
false , throw a TypeError exception.
Let C be ? SpeciesConstructor (promise ,
%Promise% ).
Let resultCapability be ? NewPromiseCapability (C ).
Return PerformPromiseThen (promise ,
onFulfilled , onRejected , resultCapability ).
27.2.5.4.1 PerformPromiseThen ( promise ,
onFulfilled , onRejected [ , resultCapability ] )
The abstract operation PerformPromiseThen takes arguments promise (a Promise),
onFulfilled (an ECMAScript language
value ), and onRejected (an ECMAScript language value )
and optional argument resultCapability (a PromiseCapability Record )
and returns an ECMAScript language value .
It performs the “then” operation on promise using onFulfilled and
onRejected as its settlement actions. If resultCapability is
passed, the result is stored by updating resultCapability 's promise. If it is
not passed, then PerformPromiseThen is being called by a specification-internal
operation where the result does not matter. It performs the following steps when called:
Assert : IsPromise (promise ) is
true .
If resultCapability is not present, then
Set resultCapability to undefined .
If IsCallable (onFulfilled )
is false , then
Let onFulfilledJobCallback be empty .
Else,
Let onFulfilledJobCallback be HostMakeJobCallback (onFulfilled ).
If IsCallable (onRejected )
is false , then
Let onRejectedJobCallback be empty .
Else,
Let onRejectedJobCallback be HostMakeJobCallback (onRejected ).
Let fulfillReaction be the PromiseReaction
Record { [[Capability]] :
resultCapability , [[Type]] :
fulfill , [[Handler]] :
onFulfilledJobCallback }.
Let rejectReaction be the PromiseReaction
Record { [[Capability]] :
resultCapability , [[Type]] :
reject , [[Handler]] :
onRejectedJobCallback }.
If promise .[[PromiseState]] is
pending , then
Append fulfillReaction to promise .[[PromiseFulfillReactions]] .
Append rejectReaction to promise .[[PromiseRejectReactions]] .
Else if promise .[[PromiseState]] is
fulfilled , then
Let value be promise .[[PromiseResult]] .
Let fulfillJob be NewPromiseReactionJob (fulfillReaction ,
value ).
Perform HostEnqueuePromiseJob (fulfillJob .[[Job]] , fulfillJob .[[Realm]] ).
Else,
Assert : promise .[[PromiseState]] is
rejected .
Let reason be promise .[[PromiseResult]] .
If promise .[[PromiseIsHandled]] is
false , perform HostPromiseRejectionTracker (promise ,
"handle" ).
Let rejectJob be NewPromiseReactionJob (rejectReaction ,
reason ).
Perform HostEnqueuePromiseJob (rejectJob .[[Job]] , rejectJob .[[Realm]] ).
Set promise .[[PromiseIsHandled]] to
true .
If resultCapability is undefined , then
Return undefined .
Else,
Return resultCapability .[[Promise]] .
27.2.5.5 Promise.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Promise" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.2.6 Properties of Promise Instances
Promise instances are ordinary objects that inherit properties from the
Promise prototype
object (the intrinsic, %Promise.prototype% ).
Promise instances are initially created with the internal slots described in Table 92 .
Table 92: Internal Slots of Promise Instances
Internal Slot
Type
Description
[[PromiseState]]
pending , fulfilled , or
rejected
Governs how a promise will react to incoming calls to its then
method.
[[PromiseResult]]
an ECMAScript language
value or empty
The value with which the promise has been fulfilled or rejected, if any.
empty if and only if the [[PromiseState]] is pending .
[[PromiseFulfillReactions]]
a List
of PromiseReaction
Records
Records
to be processed when/if the promise transitions from the
pending state to the fulfilled
state.
[[PromiseRejectReactions]]
a List
of PromiseReaction
Records
Records
to be processed when/if the promise transitions from the
pending state to the rejected
state.
[[PromiseIsHandled]]
a Boolean
Indicates whether the promise has ever had a fulfillment or rejection
handler; used in unhandled rejection tracking.
27.3 GeneratorFunction Objects
GeneratorFunctions are functions that are usually created by evaluating GeneratorDeclaration s, GeneratorExpression s, and
GeneratorMethod s. They may also
be created by calling the %GeneratorFunction% intrinsic.
Figure 6 (Informative): Generator Objects Relationships
27.3.1 The GeneratorFunction Constructor
The GeneratorFunction constructor :
is %GeneratorFunction% .
is a subclass of Function.
creates and initializes a new GeneratorFunction when called as a function rather than as a
constructor . Thus the function call
GeneratorFunction (…) is equivalent to the object creation expression
new GeneratorFunction (…) with the same arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
GeneratorFunction behaviour must include a super call to the GeneratorFunction
constructor to create and initialize subclass
instances with the internal slots necessary for built-in GeneratorFunction behaviour. All
ECMAScript syntactic forms for defining generator function objects create direct
instances of GeneratorFunction. There is no syntactic means to create instances of
GeneratorFunction subclasses.
27.3.1.1 GeneratorFunction ( ...parameterArgs ,
bodyArg )
The last argument (if any) specifies the body (executable code) of a generator function; any
preceding arguments specify formal parameters.
This function performs the following steps when called:
Let C be the active function object .
If bodyArg is not present, set bodyArg to the empty String.
Return ? CreateDynamicFunction (C ,
NewTarget, generator , parameterArgs ,
bodyArg ).
Note
27.3.2 Properties of the GeneratorFunction Constructor
The GeneratorFunction constructor :
is a standard built-in function object that inherits from the
Function constructor .
has a [[Prototype]] internal slot whose value is %Function% .
has a
"length" property whose value is 1 𝔽 .
has a "name" property whose value is
"GeneratorFunction" .
has the following properties:
27.3.2.1 GeneratorFunction.prototype
The initial value of GeneratorFunction.prototype is the GeneratorFunction
prototype object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
27.3.3 Properties of the GeneratorFunction Prototype Object
The GeneratorFunction prototype object :
27.3.3.1 GeneratorFunction.prototype.constructor
The initial value of GeneratorFunction.prototype.constructor is %GeneratorFunction% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.3.3.2 GeneratorFunction.prototype.prototype
The initial value of GeneratorFunction.prototype.prototype is %GeneratorPrototype% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.3.3.3 GeneratorFunction.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "GeneratorFunction" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.3.4 GeneratorFunction Instances
Every GeneratorFunction instance is an ECMAScript function object and has the
internal slots listed in Table
30 . The value of the [[IsClassConstructor]]
internal slot for all such instances is false .
Each GeneratorFunction instance has the following own properties:
27.3.4.1 length
The specification for the "length" property of Function instances given in
20.2.4.1 also applies to
GeneratorFunction instances.
27.3.4.2 name
The specification for the "name" property of Function instances given in
20.2.4.2 also applies to
GeneratorFunction instances.
27.3.4.3 prototype
Whenever a GeneratorFunction instance is created another ordinary object is also
created and is the initial value of the generator function's "prototype"
property. The value of the prototype property is used to initialize the [[Prototype]] internal slot of a newly created Generator when the
generator function object is invoked using [[Call]] .
This property has the attributes { [[Writable]] :
true , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
Unlike Function instances, the object that is the value of a GeneratorFunction's
"prototype" property does not have a
"constructor" property whose value is the GeneratorFunction
instance.
27.4 AsyncGeneratorFunction Objects
AsyncGeneratorFunctions are functions that are usually created by evaluating AsyncGeneratorDeclaration , AsyncGeneratorExpression ,
and AsyncGeneratorMethod
syntactic productions. They may also be created by calling the %AsyncGeneratorFunction%
intrinsic.
27.4.1 The AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction constructor :
is %AsyncGeneratorFunction% .
is a subclass of Function.
creates and initializes a new AsyncGeneratorFunction when called as a function rather than
as a constructor . Thus the function call
AsyncGeneratorFunction (...) is equivalent to the object creation expression
new AsyncGeneratorFunction (...) with the same arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
AsyncGeneratorFunction behaviour must include a super call to the
AsyncGeneratorFunction constructor to create and initialize subclass
instances with the internal slots necessary for built-in AsyncGeneratorFunction behaviour.
All ECMAScript syntactic forms for defining async generator function
objects create direct instances of AsyncGeneratorFunction. There is
no syntactic means to create instances of AsyncGeneratorFunction subclasses.
27.4.1.1 AsyncGeneratorFunction ( ...parameterArgs ,
bodyArg )
The last argument (if any) specifies the body (executable code) of an async generator
function; any preceding arguments specify formal parameters.
This function performs the following steps when called:
Let C be the active function object .
If bodyArg is not present, set bodyArg to the empty String.
Return ? CreateDynamicFunction (C ,
NewTarget, async-generator , parameterArgs ,
bodyArg ).
Note
27.4.2 Properties of the AsyncGeneratorFunction Constructor
The AsyncGeneratorFunction constructor :
is a standard built-in function object that inherits from the
Function constructor .
has a [[Prototype]] internal slot whose value is %Function% .
has a "length" property
whose value is 1 𝔽 .
has a "name" property whose value is
"AsyncGeneratorFunction" .
has the following properties:
27.4.2.1 AsyncGeneratorFunction.prototype
The initial value of AsyncGeneratorFunction.prototype is the AsyncGeneratorFunction
prototype object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
27.4.3 Properties of the AsyncGeneratorFunction Prototype Object
The AsyncGeneratorFunction prototype object :
27.4.3.1 AsyncGeneratorFunction.prototype.constructor
The initial value of AsyncGeneratorFunction.prototype.constructor is %AsyncGeneratorFunction% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.4.3.2 AsyncGeneratorFunction.prototype.prototype
The initial value of AsyncGeneratorFunction.prototype.prototype is %AsyncGeneratorPrototype% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.4.3.3 AsyncGeneratorFunction.prototype [ %Symbol.toStringTag%
]
The initial value of the %Symbol.toStringTag% property is the
String value "AsyncGeneratorFunction" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.4.4 AsyncGeneratorFunction Instances
Every AsyncGeneratorFunction instance is an ECMAScript function object and has the
internal slots listed in Table
30 . The value of the [[IsClassConstructor]]
internal slot for all such instances is false .
Each AsyncGeneratorFunction instance has the following own properties:
27.4.4.1 length
The value of the "length" property is an integral Number that indicates
the typical number of arguments expected by the AsyncGeneratorFunction. However, the
language permits the function to be invoked with some other number of arguments. The
behaviour of an AsyncGeneratorFunction when invoked on a number of arguments other than the
number specified by its "length" property depends on the function.
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.4.4.2 name
The specification for the "name" property of Function instances given in
20.2.4.2 also applies to
AsyncGeneratorFunction instances.
27.4.4.3 prototype
Whenever an AsyncGeneratorFunction instance is created, another ordinary
object is also created and is the initial value of the async
generator function's "prototype" property. The value of the prototype
property is used to initialize the [[Prototype]] internal slot of a
newly created AsyncGenerator when the generator function object is invoked
using [[Call]] .
This property has the attributes { [[Writable]] :
true , [[Enumerable]] : false ,
[[Configurable]] : false }.
Note
Unlike function instances, the object that is the value of an
AsyncGeneratorFunction's "prototype" property does not have a
"constructor" property whose value is the AsyncGeneratorFunction
instance.
27.5 Generator Objects
A Generator is created by calling a generator function and conforms to both the iterator
interface and the iterable interface .
Generator instances directly inherit properties from the initial value of the
"prototype" property of the generator function that created the instance.
Generator instances indirectly inherit properties from %GeneratorPrototype% .
27.5.1 The %GeneratorPrototype% Object
The %GeneratorPrototype% object:
is %GeneratorFunction.prototype.prototype% .
is an ordinary
object .
is not a Generator instance and does not have a [[GeneratorState]]
internal slot.
has a [[Prototype]] internal slot whose value is %Iterator.prototype% .
has properties that are indirectly inherited by all Generator instances.
27.5.1.1 %GeneratorPrototype%.constructor
The initial value of %GeneratorPrototype% .constructor
is %GeneratorFunction.prototype% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.5.1.2 %GeneratorPrototype%.next ( value )
Return ? GeneratorResume (this
value, value , empty ).
27.5.1.3 %GeneratorPrototype%.return ( value )
This method performs the following steps when called:
Let g be the this value.
Let C be ReturnCompletion (value ).
Return ? GeneratorResumeAbrupt (g ,
C , empty ).
27.5.1.4 %GeneratorPrototype%.throw ( exception )
This method performs the following steps when called:
Let g be the this value.
Let C be ThrowCompletion (exception ).
Return ? GeneratorResumeAbrupt (g ,
C , empty ).
27.5.1.5 %GeneratorPrototype% [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Generator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.5.2 Properties of Generator Instances
Generator instances are initially created with the internal slots described in Table 93 .
Table 93: Internal Slots of Generator Instances
Internal Slot
Type
Description
[[GeneratorState]]
suspended-start ,
suspended-yield , executing , or
completed
The current execution state of the generator.
[[GeneratorContext]]
an execution context
The execution context that
is used when executing the code of this generator.
[[GeneratorBrand]]
a String or empty
A brand used to distinguish different kinds of generators. The [[GeneratorBrand]] of generators declared by
ECMAScript source text is
always empty .
27.5.3 Generator Abstract Operations
27.5.3.1 GeneratorStart ( generator ,
generatorBody )
The abstract operation GeneratorStart takes arguments generator (a Generator) and
generatorBody (a FunctionBody Parse
Node or an Abstract Closure with no parameters) and
returns unused . It performs the following steps when called:
Assert :
generator .[[GeneratorState]] is
suspended-start .
Let genContext be the running execution
context .
Set the Generator component of genContext to generator .
Let closure be a new Abstract Closure
with no parameters that captures generatorBody and performs the following
steps when called:
Let acGenContext be the running execution
context .
Let acGenerator be the Generator component of
acGenContext .
If generatorBody is a Parse
Node , then
Let result be Completion (Evaluation of
generatorBody ).
Else,
Assert :
generatorBody is an Abstract Closure
with no parameters.
Let result be Completion (generatorBody ()).
Assert : If we return here, the
generator either threw an exception or performed either an implicit or
explicit return.
Remove acGenContext from the execution context
stack and restore the execution context that
is at the top of the execution context
stack as the running execution
context .
Set acGenerator .[[GeneratorState]] to
completed .
NOTE: Once a generator enters the completed state it
never leaves it and its associated execution
context is never resumed. Any execution state
associated with acGenerator can be discarded at this point.
If result is a normal
completion , then
Let resultValue be undefined .
Else if result is a return
completion , then
Let resultValue be result .[[Value]] .
Else,
Assert : result is a
throw
completion .
Return ? result .
Return NormalCompletion (CreateIteratorResultObject (resultValue ,
true )).
Set the code evaluation state of genContext such that when evaluation is
resumed for that execution context ,
closure will be called with no arguments.
Set generator .[[GeneratorContext]] to
genContext .
Return unused .
27.5.3.2 GeneratorValidate ( generator ,
generatorBrand )
The abstract operation GeneratorValidate takes arguments generator (an ECMAScript language value ) and
generatorBrand (a String or empty ) and returns either a
normal completion
containing one of suspended-start ,
suspended-yield , or completed , or a throw completion . It
performs the following steps when called:
Perform ? RequireInternalSlot (generator ,
[[GeneratorState]] ).
Perform ? RequireInternalSlot (generator ,
[[GeneratorBrand]] ).
If generator .[[GeneratorBrand]] is not
generatorBrand , throw a TypeError exception.
Assert :
generator also has a [[GeneratorContext]]
internal slot.
Let state be generator .[[GeneratorState]] .
If state is executing , throw a
TypeError exception.
Return state .
27.5.3.3 GeneratorResume ( generator ,
value , generatorBrand )
The abstract operation GeneratorResume takes arguments generator (an ECMAScript language value ),
value (an ECMAScript language value or
empty ), and generatorBrand (a String or
empty ) and returns either a normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Let state be ? GeneratorValidate (generator ,
generatorBrand ).
If state is completed , return CreateIteratorResultObject (undefined ,
true ).
Assert :
state is either suspended-start or
suspended-yield .
Let genContext be generator .[[GeneratorContext]] .
Let methodContext be the running execution
context .
Suspend methodContext .
Set generator .[[GeneratorState]] to
executing .
Push genContext onto the execution context
stack ; genContext is now the running execution context .
Resume the suspended evaluation of
genContext using NormalCompletion (value )
as the result of the operation that suspended it. Let result be the value
returned by the resumed computation.
Assert :
When we return here, genContext has already been removed from the
execution context stack and
methodContext is the currently running execution context .
Return ? result .
27.5.3.4 GeneratorResumeAbrupt ( generator ,
abruptCompletion , generatorBrand )
The abstract operation GeneratorResumeAbrupt takes arguments generator (an
ECMAScript language value ),
abruptCompletion (a return
completion or a throw completion ),
and generatorBrand (a String or empty ) and returns either
a normal completion
containing an ECMAScript language
value or a throw
completion . It performs the following steps when called:
Let state be ? GeneratorValidate (generator ,
generatorBrand ).
If state is suspended-start , then
Set generator .[[GeneratorState]] to
completed .
NOTE: Once a generator enters the completed state it
never leaves it and its associated execution
context is never resumed. Any execution state
associated with generator can be discarded at this point.
Set state to completed .
If state is completed , then
If abruptCompletion is a return
completion , then
Return CreateIteratorResultObject (abruptCompletion .[[Value]] , true ).
Return ? abruptCompletion .
Assert :
state is suspended-yield .
Let genContext be generator .[[GeneratorContext]] .
Let methodContext be the running execution
context .
Suspend methodContext .
Set generator .[[GeneratorState]] to
executing .
Push genContext onto the execution context
stack ; genContext is now the running execution context .
Resume the suspended evaluation of
genContext using abruptCompletion as the result of
the operation that suspended it. Let result be the Completion
Record returned by the resumed computation.
Assert :
When we return here, genContext has already been removed from the
execution context stack and
methodContext is the currently running execution context .
Return ? result .
27.5.3.5 GetGeneratorKind ( )
The abstract operation GetGeneratorKind takes no arguments and returns
non-generator , sync , or
async . It performs the following steps when called:
Let genContext be the running execution
context .
If genContext does not have a Generator component, return
non-generator .
Let generator be the Generator component of genContext .
If generator has an [[AsyncGeneratorState]]
internal slot, return async .
Else, return sync .
27.5.3.6 GeneratorYield ( iteratorResult )
The abstract operation GeneratorYield takes argument iteratorResult (an Object
that conforms to the IteratorResult interface ) and
returns either a normal completion
containing an ECMAScript language
value or an abrupt completion .
It performs the following steps when called:
Let genContext be the running execution
context .
Assert :
genContext is the execution
context of a generator.
Let generator be the value of the Generator component of
genContext .
Assert :
GetGeneratorKind () is
sync .
Set generator .[[GeneratorState]] to
suspended-yield .
Remove genContext from the execution context
stack and restore the execution context that is at
the top of the execution context stack as
the running execution context .
Let callerContext be the running execution
context .
Resume callerContext passing NormalCompletion (iteratorResult ).
If genContext is ever resumed again, let resumptionValue be
the Completion
Record with which it is resumed.
Assert : If
control reaches here, then genContext is the running execution context
again.
Return resumptionValue .
27.5.3.7 Yield ( value )
The abstract operation Yield takes argument value (an ECMAScript language value ) and
returns either a normal completion
containing an ECMAScript language
value or an abrupt completion .
It performs the following steps when called:
Let generatorKind be GetGeneratorKind ().
If generatorKind is async , return ? AsyncGeneratorYield (? Await (value )).
Otherwise, return ? GeneratorYield (CreateIteratorResultObject (value ,
false )).
27.5.3.8 CreateIteratorFromClosure ( closure ,
generatorBrand , generatorPrototype [ , extraSlots ] )
The abstract operation CreateIteratorFromClosure takes arguments closure (an
Abstract Closure with no parameters),
generatorBrand (a String or empty ), and
generatorPrototype (an Object) and optional argument extraSlots (a
List of names of
internal slots) and returns a Generator. It performs the following steps when called:
NOTE: closure can contain uses of the Yield operation to yield an
IteratorResult object .
If extraSlots is not present, set extraSlots to a new empty
List .
Let internalSlotsList be the list-concatenation
of extraSlots and « [[GeneratorState]] , [[GeneratorContext]] , [[GeneratorBrand]] ».
Let generator be OrdinaryObjectCreate (generatorPrototype ,
internalSlotsList ).
Set generator .[[GeneratorBrand]] to
generatorBrand .
Set generator .[[GeneratorState]] to
suspended-start .
Let callerContext be the running execution
context .
Let calleeContext be a new execution
context .
Set the Function of calleeContext to null .
Set the Realm of calleeContext to the current Realm
Record .
Set the ScriptOrModule of calleeContext to callerContext 's
ScriptOrModule.
If callerContext is not already suspended, suspend
callerContext .
Push calleeContext onto the execution context
stack ; calleeContext is now the running execution context .
Perform GeneratorStart (generator ,
closure ).
Remove calleeContext from the execution context
stack and restore callerContext as the running execution context .
Return generator .
27.6 AsyncGenerator Objects
An AsyncGenerator is created by calling an async generator function and conforms to both the
async iterator interface and the
async iterable interface .
AsyncGenerator instances directly inherit properties from the initial value of the
"prototype" property of the async generator function that created the instance.
AsyncGenerator instances indirectly inherit properties from %AsyncGeneratorPrototype% .
27.6.1 The %AsyncGeneratorPrototype% Object
The %AsyncGeneratorPrototype% object:
is %AsyncGeneratorFunction.prototype.prototype% .
is an ordinary
object .
is not an AsyncGenerator instance and does not have an [[AsyncGeneratorState]] internal slot.
has a [[Prototype]] internal slot whose value is %AsyncIteratorPrototype% .
has properties that are indirectly inherited by all AsyncGenerator instances.
27.6.1.1 %AsyncGeneratorPrototype%.constructor
The initial value of %AsyncGeneratorPrototype% .constructor
is %AsyncGeneratorFunction.prototype% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.6.1.2 %AsyncGeneratorPrototype%.next ( value )
Let generator be the this value.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let result be Completion (AsyncGeneratorValidate (generator ,
empty )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Let state be generator .[[AsyncGeneratorState]] .
If state is completed , then
Let iteratorResult be CreateIteratorResultObject (undefined ,
true ).
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
iteratorResult »).
Return promiseCapability .[[Promise]] .
Let completion be NormalCompletion (value ).
Perform AsyncGeneratorEnqueue (generator ,
completion , promiseCapability ).
If state is either suspended-start or
suspended-yield , then
Perform AsyncGeneratorResume (generator ,
completion ).
Else,
Assert : state is either
executing or draining-queue .
Return promiseCapability .[[Promise]] .
27.6.1.3 %AsyncGeneratorPrototype%.return ( value )
Let generator be the this value.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let result be Completion (AsyncGeneratorValidate (generator ,
empty )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Let completion be ReturnCompletion (value ).
Perform AsyncGeneratorEnqueue (generator ,
completion , promiseCapability ).
Let state be generator .[[AsyncGeneratorState]] .
If state is either suspended-start or
completed , then
Set generator .[[AsyncGeneratorState]] to
draining-queue .
Perform AsyncGeneratorAwaitReturn (generator ).
Else if state is suspended-yield , then
Perform AsyncGeneratorResume (generator ,
completion ).
Else,
Assert : state is either
executing or draining-queue .
Return promiseCapability .[[Promise]] .
27.6.1.4 %AsyncGeneratorPrototype%.throw ( exception
)
Let generator be the this value.
Let promiseCapability be ! NewPromiseCapability (%Promise% ).
Let result be Completion (AsyncGeneratorValidate (generator ,
empty )).
IfAbruptRejectPromise (result ,
promiseCapability ).
Let state be generator .[[AsyncGeneratorState]] .
If state is suspended-start , then
Set generator .[[AsyncGeneratorState]] to
completed .
Set state to completed .
If state is completed , then
Perform ! Call (promiseCapability .[[Reject]] , undefined , «
exception »).
Return promiseCapability .[[Promise]] .
Let completion be ThrowCompletion (exception ).
Perform AsyncGeneratorEnqueue (generator ,
completion , promiseCapability ).
If state is suspended-yield , then
Perform AsyncGeneratorResume (generator ,
completion ).
Else,
Assert : state is either
executing or draining-queue .
Return promiseCapability .[[Promise]] .
27.6.1.5 %AsyncGeneratorPrototype% [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "AsyncGenerator" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.6.2 Properties of AsyncGenerator Instances
AsyncGenerator instances are initially created with the internal slots described below:
Table 94: Internal Slots of AsyncGenerator Instances
Internal Slot
Type
Description
[[AsyncGeneratorState]]
suspended-start ,
suspended-yield , executing ,
draining-queue , or completed
The current execution state of the async generator.
[[AsyncGeneratorContext]]
an execution context
The execution context that
is used when executing the code of this async generator.
[[AsyncGeneratorQueue]]
a List
of AsyncGeneratorRequest
Records
Records
which represent requests to resume the async generator. Except during state
transitions, it is non-empty if and only if [[AsyncGeneratorState]] is either
executing or draining-queue .
[[GeneratorBrand]]
a String or empty
A brand used to distinguish different kinds of async generators. The [[GeneratorBrand]] of async generators declared by
ECMAScript source text is
always empty .
27.6.3 AsyncGenerator Abstract Operations
27.6.3.1 AsyncGeneratorRequest Records
An AsyncGeneratorRequest is a
Record value used to
store information about how an async generator should be resumed and contains capabilities
for fulfilling or rejecting the corresponding promise.
They have the following fields:
Table 95: AsyncGeneratorRequest Record Fields
27.6.3.2 AsyncGeneratorStart ( generator ,
generatorBody )
The abstract operation AsyncGeneratorStart takes arguments generator (an
AsyncGenerator) and generatorBody (a FunctionBody Parse
Node or an Abstract Closure with no parameters) and
returns unused . It performs the following steps when called:
Assert :
generator .[[AsyncGeneratorState]] is
suspended-start .
Let genContext be the running execution
context .
Set the Generator component of genContext to generator .
Let closure be a new Abstract Closure
with no parameters that captures generatorBody and performs the following
steps when called:
Let acGenContext be the running execution
context .
Let acGenerator be the Generator component of
acGenContext .
If generatorBody is a Parse
Node , then
Let result be Completion (Evaluation of
generatorBody ).
Else,
Assert :
generatorBody is an Abstract Closure
with no parameters.
Let result be Completion (generatorBody ()).
Assert : If we return here, the async
generator either threw an exception or performed either an implicit or
explicit return.
Remove acGenContext from the execution context
stack and restore the execution context that
is at the top of the execution context
stack as the running execution
context .
Set acGenerator .[[AsyncGeneratorState]]
to draining-queue .
If result is a normal
completion , set result to NormalCompletion (undefined ).
If result is a return
completion , set result to NormalCompletion (result .[[Value]] ).
Perform AsyncGeneratorCompleteStep (acGenerator ,
result , true ).
Perform AsyncGeneratorDrainQueue (acGenerator ).
Return NormalCompletion (undefined ).
Set the code evaluation state of genContext such that when evaluation is
resumed for that execution context ,
closure will be called with no arguments.
Set generator .[[AsyncGeneratorContext]] to
genContext .
Set generator .[[AsyncGeneratorQueue]] to a new
empty List .
Return unused .
27.6.3.3 AsyncGeneratorValidate ( generator ,
generatorBrand )
The abstract operation AsyncGeneratorValidate takes arguments generator (an
ECMAScript language value ) and
generatorBrand (a String or empty ) and returns either a
normal completion
containing unused or a throw completion . It
performs the following steps when called:
Perform ? RequireInternalSlot (generator ,
[[AsyncGeneratorContext]] ).
Perform ? RequireInternalSlot (generator ,
[[AsyncGeneratorState]] ).
Perform ? RequireInternalSlot (generator ,
[[AsyncGeneratorQueue]] ).
If generator .[[GeneratorBrand]] is not
generatorBrand , throw a TypeError exception.
Return unused .
27.6.3.4 AsyncGeneratorEnqueue ( generator ,
completion , promiseCapability )
The abstract operation AsyncGeneratorEnqueue takes arguments generator (an
AsyncGenerator), completion (a Completion Record ),
and promiseCapability (a PromiseCapability
Record ) and returns unused . It performs the
following steps when called:
Let request be AsyncGeneratorRequest
{ [[Completion]] : completion , [[Capability]] : promiseCapability }.
Append request to generator .[[AsyncGeneratorQueue]] .
Return unused .
27.6.3.5 AsyncGeneratorCompleteStep ( generator ,
completion , done [ , realm ] )
The abstract operation AsyncGeneratorCompleteStep takes arguments generator (an
AsyncGenerator), completion (a Completion Record ),
and done (a Boolean) and optional argument realm (a Realm
Record ) and returns unused . It performs the
following steps when called:
Assert :
generator .[[AsyncGeneratorQueue]] is not empty.
Let next be the first element of generator .[[AsyncGeneratorQueue]] .
Remove the first element from generator .[[AsyncGeneratorQueue]] .
Let promiseCapability be next .[[Capability]] .
Let value be completion .[[Value]] .
If completion is a throw
completion , then
Perform ! Call (promiseCapability .[[Reject]] , undefined , «
value »).
Else,
Assert : completion is a
normal
completion .
If realm is present, then
Let oldRealm be the running execution
context 's Realm .
Set the running
execution context 's Realm to
realm .
Let iteratorResult be CreateIteratorResultObject (value ,
done ).
Set the running
execution context 's Realm to
oldRealm .
Else,
Let iteratorResult be CreateIteratorResultObject (value ,
done ).
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
iteratorResult »).
Return unused .
27.6.3.6 AsyncGeneratorResume ( generator ,
completion )
The abstract operation AsyncGeneratorResume takes arguments generator (an
AsyncGenerator) and completion (a Completion Record )
and returns unused . It performs the following steps when called:
Assert :
generator .[[AsyncGeneratorState]] is either
suspended-start or suspended-yield .
Let genContext be generator .[[AsyncGeneratorContext]] .
Let callerContext be the running execution
context .
Suspend callerContext .
Set generator .[[AsyncGeneratorState]] to
executing .
Push genContext onto the execution context
stack ; genContext is now the running execution context .
Resume the suspended evaluation of
genContext using completion as the result of the
operation that suspended it. Let result be the Completion
Record returned by the resumed computation.
Assert :
result is never an abrupt
completion .
Assert :
When we return here, genContext has already been removed from the
execution context stack and
callerContext is the currently running execution context .
Return unused .
27.6.3.7 AsyncGeneratorUnwrapYieldResumption (
resumptionValue )
The abstract operation AsyncGeneratorUnwrapYieldResumption takes argument
resumptionValue (a Completion
Record ) and returns either a normal completion
containing an ECMAScript language
value or an abrupt completion .
It performs the following steps when called:
If resumptionValue is not a return
completion , return ? resumptionValue .
Let awaited be Completion (Await (resumptionValue .[[Value]] )).
If awaited is a throw
completion , return ? awaited .
Assert :
awaited is a normal
completion .
Return ReturnCompletion (awaited .[[Value]] ).
27.6.3.8 AsyncGeneratorYield ( value )
The abstract operation AsyncGeneratorYield takes argument value (an ECMAScript language value ) and
returns either a normal completion
containing an ECMAScript language
value or an abrupt completion .
It performs the following steps when called:
Let genContext be the running execution
context .
Assert :
genContext is the execution
context of a generator.
Let generator be the value of the Generator component of
genContext .
Assert :
GetGeneratorKind () is
async .
Let completion be NormalCompletion (value ).
Assert :
The execution context stack has
at least two elements.
Let previousContext be the second to top element of the execution context stack .
Let previousRealm be previousContext 's Realm .
Perform AsyncGeneratorCompleteStep (generator ,
completion , false , previousRealm ).
Let queue be generator .[[AsyncGeneratorQueue]] .
If queue is not empty, then
NOTE: Execution continues without suspending the generator.
Let toYield be the first element of queue .
Let resumptionValue be Completion (toYield .[[Completion]] ).
Return ? AsyncGeneratorUnwrapYieldResumption (resumptionValue ).
Else,
Set generator .[[AsyncGeneratorState]] to
suspended-yield .
Remove genContext from the execution context
stack and restore the execution context that
is at the top of the execution context
stack as the running execution
context .
Let callerContext be the running execution
context .
Resume callerContext passing undefined . If
genContext is ever resumed again, let resumptionValue
be the Completion
Record with which it is resumed.
Assert : If control reaches here, then
genContext is the running execution
context again.
Return ? AsyncGeneratorUnwrapYieldResumption (resumptionValue ).
27.6.3.9 AsyncGeneratorAwaitReturn ( generator )
The abstract operation AsyncGeneratorAwaitReturn takes argument generator (an
AsyncGenerator) and returns unused . It performs the following steps
when called:
Assert :
generator .[[AsyncGeneratorState]] is
draining-queue .
Let queue be generator .[[AsyncGeneratorQueue]] .
Assert :
queue is not empty.
Let next be the first element of queue .
Let completion be Completion (next .[[Completion]] ).
Assert :
completion is a return
completion .
Let promiseCompletion be Completion (PromiseResolve (%Promise% ,
completion .[[Value]] )).
If promiseCompletion is an abrupt
completion , then
Perform AsyncGeneratorCompleteStep (generator ,
promiseCompletion , true ).
Perform AsyncGeneratorDrainQueue (generator ).
Return unused .
Assert :
promiseCompletion is a normal
completion .
Let promise be promiseCompletion .[[Value]] .
Let fulfilledClosure be a new Abstract Closure
with parameters (value ) that captures generator and performs
the following steps when called:
Assert : generator .[[AsyncGeneratorState]] is
draining-queue .
Let result be NormalCompletion (value ).
Perform AsyncGeneratorCompleteStep (generator ,
result , true ).
Perform AsyncGeneratorDrainQueue (generator ).
Return NormalCompletion (undefined ).
Let onFulfilled be CreateBuiltinFunction (fulfilledClosure ,
1, "" , « »).
Let rejectedClosure be a new Abstract Closure
with parameters (reason ) that captures generator and performs
the following steps when called:
Assert : generator .[[AsyncGeneratorState]] is
draining-queue .
Let result be ThrowCompletion (reason ).
Perform AsyncGeneratorCompleteStep (generator ,
result , true ).
Perform AsyncGeneratorDrainQueue (generator ).
Return NormalCompletion (undefined ).
Let onRejected be CreateBuiltinFunction (rejectedClosure ,
1, "" , « »).
Perform PerformPromiseThen (promise ,
onFulfilled , onRejected ).
Return unused .
27.6.3.10 AsyncGeneratorDrainQueue ( generator )
The abstract operation AsyncGeneratorDrainQueue takes argument generator (an
AsyncGenerator) and returns unused . It drains the generator's
AsyncGeneratorQueue until it encounters an AsyncGeneratorRequest which
holds a return completion .
It performs the following steps when called:
Assert :
generator .[[AsyncGeneratorState]] is
draining-queue .
Let queue be generator .[[AsyncGeneratorQueue]] .
Repeat, while queue is not empty,
Let next be the first element of queue .
Let completion be Completion (next .[[Completion]] ).
If completion is a return
completion , then
Perform AsyncGeneratorAwaitReturn (generator ).
Return unused .
Else,
If completion is a normal
completion , then
Set completion to NormalCompletion (undefined ).
Perform AsyncGeneratorCompleteStep (generator ,
completion , true ).
Set generator .[[AsyncGeneratorState]] to
completed .
Return unused .
27.6.3.11 CreateAsyncIteratorFromClosure ( closure ,
generatorBrand , generatorPrototype )
The abstract operation CreateAsyncIteratorFromClosure takes arguments closure (an
Abstract Closure with no parameters),
generatorBrand (a String or empty ), and
generatorPrototype (an Object) and returns an AsyncGenerator. It performs the
following steps when called:
NOTE: closure can contain uses of the Await operation and uses of the
Yield
operation to yield an IteratorResult
object .
Let internalSlotsList be « [[AsyncGeneratorState]] , [[AsyncGeneratorContext]] , [[AsyncGeneratorQueue]] , [[GeneratorBrand]] ».
Let generator be OrdinaryObjectCreate (generatorPrototype ,
internalSlotsList ).
Set generator .[[GeneratorBrand]] to
generatorBrand .
Set generator .[[AsyncGeneratorState]] to
suspended-start .
Let callerContext be the running execution
context .
Let calleeContext be a new execution
context .
Set the Function of calleeContext to null .
Set the Realm of calleeContext to the current Realm
Record .
Set the ScriptOrModule of calleeContext to callerContext 's
ScriptOrModule.
If callerContext is not already suspended, suspend
callerContext .
Push calleeContext onto the execution context
stack ; calleeContext is now the running execution context .
Perform AsyncGeneratorStart (generator ,
closure ).
Remove calleeContext from the execution context
stack and restore callerContext as the running execution context .
Return generator .
27.7 AsyncFunction Objects
AsyncFunctions are functions that are usually created by evaluating AsyncFunctionDeclaration s, AsyncFunctionExpression s,
AsyncMethod s, and AsyncArrowFunction s. They may
also be created by calling the %AsyncFunction% intrinsic.
27.7.1 The AsyncFunction Constructor
The AsyncFunction constructor :
is %AsyncFunction% .
is a subclass of Function.
creates and initializes a new AsyncFunction when called as a function rather than as a
constructor . Thus the function call
AsyncFunction(…) is equivalent to the object creation expression
new AsyncFunction(…) with the same arguments.
may be used as the value of an extends clause of a class definition. Subclass
constructors that intend to inherit the specified
AsyncFunction behaviour must include a super call to the AsyncFunction
constructor to create and initialize a subclass
instance with the internal slots necessary for built-in async function behaviour. All
ECMAScript syntactic forms for defining async function objects create direct
instances of AsyncFunction. There is no syntactic means to create instances of AsyncFunction
subclasses.
27.7.1.1 AsyncFunction ( ...parameterArgs ,
bodyArg )
The last argument (if any) specifies the body (executable code) of an async function. Any
preceding arguments specify formal parameters.
This function performs the following steps when called:
Let C be the active function object .
If bodyArg is not present, set bodyArg to the empty String.
Return ? CreateDynamicFunction (C ,
NewTarget, async , parameterArgs ,
bodyArg ).
Note
27.7.2 Properties of the AsyncFunction Constructor
The AsyncFunction constructor :
is a standard built-in function object that inherits from the
Function constructor .
has a [[Prototype]] internal slot whose value is %Function% .
has a "length"
property whose value is 1 𝔽 .
has a "name" property whose value is "AsyncFunction" .
has the following properties:
27.7.2.1 AsyncFunction.prototype
The initial value of AsyncFunction.prototype is the AsyncFunction prototype
object .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
27.7.3 Properties of the AsyncFunction Prototype Object
The AsyncFunction prototype object :
27.7.3.1 AsyncFunction.prototype.constructor
The initial value of AsyncFunction.prototype.constructor is %AsyncFunction% .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.7.3.2 AsyncFunction.prototype [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "AsyncFunction" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
27.7.4 AsyncFunction Instances
Every AsyncFunction instance is an ECMAScript function object and has the
internal slots listed in Table
30 . The value of the [[IsClassConstructor]]
internal slot for all such instances is false . AsyncFunction instances are
not constructors and do not have a [[Construct]] internal method. AsyncFunction instances do not have a
prototype property as they are not constructable.
Each AsyncFunction instance has the following own properties:
27.7.4.1 length
The specification for the "length" property of Function instances given in
20.2.4.1 also applies to
AsyncFunction instances.
27.7.4.2 name
The specification for the "name" property of Function instances given in
20.2.4.2 also applies to
AsyncFunction instances.
27.7.5 Async Functions Abstract Operations
27.7.5.1 AsyncFunctionStart ( promiseCapability ,
asyncFunctionBody )
The abstract operation AsyncFunctionStart takes arguments promiseCapability (a
PromiseCapability Record ) and
asyncFunctionBody (a FunctionBody Parse
Node , an ExpressionBody Parse
Node , or an Abstract Closure with no parameters) and
returns unused . It performs the following steps when called:
Let runningContext be the running execution
context .
Let asyncContext be a copy of runningContext .
NOTE: Copying the execution state is required for AsyncBlockStart to
resume its execution. It is ill-defined to resume a currently executing context.
Perform AsyncBlockStart (promiseCapability ,
asyncFunctionBody , asyncContext ).
Return unused .
27.7.5.2 AsyncBlockStart ( promiseCapability ,
asyncBody , asyncContext )
The abstract operation AsyncBlockStart takes arguments promiseCapability (a
PromiseCapability Record ),
asyncBody (a Parse Node or an Abstract
Closure with no parameters), and asyncContext (an
execution context ) and returns
unused . It performs the following steps when called:
Let runningContext be the running execution
context .
Let closure be a new Abstract Closure
with no parameters that captures promiseCapability and
asyncBody and performs the following steps when called:
Let acAsyncContext be the running execution
context .
If asyncBody is a Parse
Node , then
Let result be Completion (Evaluation of
asyncBody ).
Else,
Assert : asyncBody
is an Abstract Closure
with no parameters.
Let result be Completion (asyncBody ()).
Assert : If we return here, the async
function either threw an exception or performed an implicit or explicit
return; all awaiting is done.
Remove acAsyncContext from the execution context
stack and restore the execution context that
is at the top of the execution context
stack as the running execution
context .
If result is a normal
completion , then
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
undefined »).
Else if result is a return
completion , then
Perform ! Call (promiseCapability .[[Resolve]] , undefined , «
result .[[Value]] »).
Else,
Assert : result is a
throw
completion .
Perform ! Call (promiseCapability .[[Reject]] , undefined , «
result .[[Value]] »).
Return NormalCompletion (unused ).
Set the code evaluation state of asyncContext such that when evaluation
is resumed for that execution context ,
closure will be called with no arguments.
Push asyncContext onto the execution context
stack ; asyncContext is now the running execution context .
Resume the suspended evaluation of
asyncContext . Let result be the value returned by
the resumed computation.
Assert :
When we return here, asyncContext has already been removed from the
execution context stack and
runningContext is the currently running execution context .
Assert :
result is a normal
completion with a value of unused . The
possible sources of this value are Await or, if the async function doesn't await
anything, step 2.i above.
Return unused .
27.7.5.3 Await ( value )
The abstract operation Await takes argument value (an ECMAScript language value ) and
returns either a normal completion
containing either an ECMAScript language
value or empty , or a throw completion . It
performs the following steps when called:
Let asyncContext be the running execution
context .
Let promise be ? PromiseResolve (%Promise% , value ).
Let fulfilledClosure be a new Abstract Closure
with parameters (v ) that captures asyncContext and performs
the following steps when called:
Let prevContext be the running execution
context .
Suspend prevContext .
Push asyncContext onto the execution context
stack ; asyncContext is now the running execution
context .
Resume the suspended evaluation of
asyncContext using NormalCompletion (v )
as the result of the operation that suspended it.
Assert : When we reach this step,
asyncContext has already been removed from the execution context
stack and prevContext is the currently
running execution
context .
Return NormalCompletion (undefined ).
Let onFulfilled be CreateBuiltinFunction (fulfilledClosure ,
1, "" , « »).
Let rejectedClosure be a new Abstract Closure
with parameters (reason ) that captures asyncContext and
performs the following steps when called:
Let prevContext be the running execution
context .
Suspend prevContext .
Push asyncContext onto the execution context
stack ; asyncContext is now the running execution
context .
Resume the suspended evaluation of
asyncContext using ThrowCompletion (reason )
as the result of the operation that suspended it.
Assert : When we reach this step,
asyncContext has already been removed from the execution context
stack and prevContext is the currently
running execution
context .
Return NormalCompletion (undefined ).
Let onRejected be CreateBuiltinFunction (rejectedClosure ,
1, "" , « »).
Perform PerformPromiseThen (promise ,
onFulfilled , onRejected ).
Remove asyncContext from the execution context
stack and restore the execution context that is at
the top of the execution context stack as
the running execution context .
Let callerContext be the running execution
context .
Resume callerContext passing empty . If
asyncContext is ever resumed again, let completion be the
Completion
Record with which it is resumed.
Assert : If
control reaches here, then asyncContext is the running execution context
again.
Return completion .
28 Reflection
28.1 The Reflect Object
The Reflect object:
is %Reflect% .
is the initial value of the "Reflect" property of the global
object .
is an ordinary
object .
has a [[Prototype]] internal slot whose value is %Object.prototype% .
is not a function
object .
does not have a [[Construct]] internal method; it cannot be used as a
constructor
with the new operator.
does not have a [[Call]] internal method; it cannot be invoked as a
function.
28.1.1 Reflect.apply ( target , thisArgument ,
argumentsList )
This function performs the following steps when called:
If IsCallable (target ) is
false , throw a TypeError exception.
Let args be ? CreateListFromArrayLike (argumentsList ).
Perform PrepareForTailCall ().
Return ? Call (target ,
thisArgument , args ).
28.1.2 Reflect.construct ( target ,
argumentsList [ , newTarget ] )
This function performs the following steps when called:
If IsConstructor (target ) is
false , throw a TypeError exception.
If newTarget is not present, set newTarget to target .
Else if IsConstructor (newTarget ) is
false , throw a TypeError exception.
Let args be ? CreateListFromArrayLike (argumentsList ).
Return ? Construct (target , args ,
newTarget ).
28.1.3 Reflect.defineProperty ( target ,
propertyKey , attributes )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
Let desc be ? ToPropertyDescriptor (attributes ).
Return ? target .[[DefineOwnProperty]] (key ,
desc ).
28.1.4 Reflect.deleteProperty ( target ,
propertyKey )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
Return ? target .[[Delete]] (key ).
28.1.5 Reflect.get ( target , propertyKey [ ,
receiver ] )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
If receiver is not present, then
Set receiver to target .
Return ? target .[[Get]] (key , receiver ).
28.1.6 Reflect.getOwnPropertyDescriptor ( target ,
propertyKey )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
Let desc be ? target .[[GetOwnProperty]] (key ).
Return FromPropertyDescriptor (desc ).
28.1.7 Reflect.getPrototypeOf ( target )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Return ? target .[[GetPrototypeOf]] () .
28.1.8 Reflect.has ( target , propertyKey )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
Return ? target .[[HasProperty]] (key ).
28.1.9 Reflect.isExtensible ( target )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Return ? target .[[IsExtensible]] () .
28.1.10 Reflect.ownKeys ( target )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let keys be ? target .[[OwnPropertyKeys]] () .
Return CreateArrayFromList (keys ).
28.1.11 Reflect.preventExtensions ( target )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Return ? target .[[PreventExtensions]] () .
28.1.12 Reflect.set ( target , propertyKey ,
V [ , receiver ] )
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
Let key be ? ToPropertyKey (propertyKey ).
If receiver is not present, then
Set receiver to target .
Return ? target .[[Set]] (key , V ,
receiver ).
28.1.13 Reflect.setPrototypeOf ( target , proto
)
This function performs the following steps when called:
If target is not an Object , throw a
TypeError exception.
If proto is not an Object and proto is
not null , throw a TypeError exception.
Return ? target .[[SetPrototypeOf]] (proto ).
28.1.14 Reflect [ %Symbol.toStringTag% ]
The initial value of the %Symbol.toStringTag% property is the
String value "Reflect" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : true }.
28.2 Proxy Objects
28.2.1 The Proxy Constructor
The Proxy constructor :
is %Proxy% .
is the initial value of the "Proxy" property of the global
object .
creates and initializes a new Proxy object when called as a constructor .
is not intended to be called as a function and will throw an exception when called in that
manner.
28.2.1.1 Proxy ( target , handler )
This function performs the following steps when called:
If NewTarget is undefined , throw a TypeError
exception.
Return ? ProxyCreate (target ,
handler ).
28.2.2 Properties of the Proxy Constructor
The Proxy constructor :
has a [[Prototype]] internal slot whose value is %Function.prototype% .
does not have a "prototype" property because Proxy objects do not have a
[[Prototype]] internal slot that requires initialization.
has the following properties:
28.2.2.1 Proxy.revocable ( target , handler
)
This function creates a revocable Proxy object.
It performs the following steps when called:
Let proxy be ? ProxyCreate (target ,
handler ).
Let revokerClosure be a new Abstract Closure
with no parameters that captures nothing and performs the following steps when
called:
Let F be the active function
object .
Let p be F .[[RevocableProxy]] .
If p is null , return NormalCompletion (undefined ).
Set F .[[RevocableProxy]] to
null .
Assert : p is a Proxy exotic object .
Set p .[[ProxyTarget]] to
null .
Set p .[[ProxyHandler]] to
null .
Return NormalCompletion (undefined ).
Let revoker be CreateBuiltinFunction (revokerClosure ,
0, "" , « [[RevocableProxy]] »).
Set revoker .[[RevocableProxy]] to
proxy .
Let result be OrdinaryObjectCreate (%Object.prototype% ).
Perform ! CreateDataPropertyOrThrow (result ,
"proxy" , proxy ).
Perform ! CreateDataPropertyOrThrow (result ,
"revoke" , revoker ).
Return result .
28.3 Module Namespace Objects
A Module Namespace Object is a module namespace exotic object that
provides runtime property-based access to a module's exported bindings. There is no constructor function
for Module Namespace Objects. Instead, such an object is created for each module that is imported by
an ImportDeclaration that
contains a NameSpaceImport .
In addition to the properties specified in 10.4.6 each Module
Namespace Object has the following own property:
28.3.1 %Symbol.toStringTag%
The initial value of the %Symbol.toStringTag% property is the
String value "Module" .
This property has the attributes { [[Writable]] :
false , [[Enumerable]] : false ,
[[Configurable]] : false }.
29 Memory Model
The memory consistency model, or memory model , specifies the possible orderings
of Shared Data Block events , arising via
accessing TypedArray
instances backed by a SharedArrayBuffer and via methods on the Atomics object. When the program has no
data races (defined below), the ordering of events appears as sequentially consistent, i.e., as an
interleaving of actions from each agent . When the program has data races, shared memory operations
may appear sequentially inconsistent. For example, programs may exhibit causality-violating behaviour
and other astonishments. These astonishments arise from compiler transforms and the design of CPUs
(e.g., out-of-order execution and speculation). The memory model defines both the precise conditions
under which a program exhibits sequentially consistent behaviour as well as the possible values read
from data races. To wit, there is no undefined behaviour.
The memory model is defined as relational constraints on events introduced by abstract operations on
SharedArrayBuffer or by methods on the Atomics object during an evaluation.
Note
This section provides an axiomatic model on events introduced by the abstract operations
on SharedArrayBuffers. It bears stressing that the model is not expressible algorithmically,
unlike the rest of this specification. The nondeterministic introduction of events by abstract operations
is the interface between the operational semantics of ECMAScript evaluation and the axiomatic
semantics of the memory model. The semantics of these events is defined by considering graphs of
all events in an evaluation. These are neither Static Semantics nor Runtime Semantics. There is
no demonstrated algorithmic implementation, but instead a set of constraints that determine if a
particular event graph is allowed or disallowed.
29.1 Memory Model Fundamentals
Shared memory accesses (reads and writes) are divided into two groups, atomic accesses and data
accesses, defined below. Atomic accesses are sequentially consistent, i.e., there is a strict total
ordering of events agreed upon by all agents in an agent cluster . Non-atomic accesses
do not have a strict total ordering agreed upon by all agents , i.e., unordered.
Note 1
No orderings weaker than sequentially consistent and stronger than unordered, such as
release-acquire, are supported.
A Shared Data Block event is either a
ReadSharedMemory , WriteSharedMemory , or ReadModifyWriteSharedMemory Record .
Table 96: ReadSharedMemory Event Fields
Field Name
Value
Meaning
[[Order]]
seq-cst or unordered
The weakest ordering guaranteed by the memory model for
the event.
[[NoTear]]
a Boolean
Whether this event is allowed to read from multiple write events with equal
range as this event.
[[Block]]
a Shared Data Block
The block the event operates on.
[[ByteIndex]]
a non-negative integer
The byte address of the read in [[Block]] .
[[ElementSize]]
a non-negative integer
The size of the read.
Table 97: WriteSharedMemory Event Fields
Field Name
Value
Meaning
[[Order]]
seq-cst , unordered , or
init
The weakest ordering guaranteed by the memory model for
the event.
[[NoTear]]
a Boolean
Whether this event is allowed to be read from multiple read events with equal
range as this event.
[[Block]]
a Shared Data Block
The block the event operates on.
[[ByteIndex]]
a non-negative integer
The byte address of the write in [[Block]] .
[[ElementSize]]
a non-negative integer
The size of the write.
[[Payload]]
a List of
byte values
The List of
byte values to be read by other
events.
Table 98: ReadModifyWriteSharedMemory
Event Fields
These events are introduced by abstract
operations or by methods on the Atomics object.
Some operations may also introduce Synchronize events. A Synchronize event has no fields, and exists
purely to directly constrain the permitted orderings of other events.
In addition to Shared
Data Block and Synchronize events, there are host -specific events.
Let the range of a ReadSharedMemory, WriteSharedMemory, or ReadModifyWriteSharedMemory event be the
Set of contiguous integers from its [[ByteIndex]] to
[[ByteIndex]] + [[ElementSize]] - 1. Two events'
ranges are equal when the events have the same [[Block]] , and the ranges
are element-wise equal. Two events' ranges are overlapping when the events have the same [[Block]] , the ranges are not equal and their intersection is non-empty. Two
events' ranges are disjoint when the events do not have the same [[Block]]
or their ranges are neither equal nor overlapping.
Note 2
Examples of host -specific synchronizing events that should be
accounted for are: sending a SharedArrayBuffer from one agent to another (e.g., by
postMessage in a browser), starting and stopping agents , and communicating within the
agent
cluster via channels other than shared memory. For a particular
execution execution , those events are provided by the host via the host-synchronizes-with strict partial order .
Additionally, hosts
can add host -specific
synchronizing events to execution .[[EventList]] so as to
participate in the is-agent-order-before Relation .
Events are ordered within candidate executions by the relations
defined below.
29.2 Agent Events Records
An Agent Events Record is a Record with the following
fields.
Table 99: Agent Events Record Fields
Field Name
Value
Meaning
[[AgentSignifier]]
an agent
signifier
The agent whose evaluation resulted in this
ordering.
[[EventList]]
a List of
events
Events are appended to the list during evaluation.
[[AgentSynchronizesWith]]
a List of
pairs of Synchronize events
Synchronize
relationships introduced by the operational semantics.
29.3 Chosen Value Records
A Chosen Value Record is a Record with the following
fields.
Table 100: Chosen Value Record Fields
29.4 Candidate Executions
A candidate execution of the evaluation of
an agent
cluster is a Record with the
following fields.
Table 101: Candidate Execution Record Fields
An empty candidate execution is a
candidate execution Record whose fields are empty
Lists .
29.5 Abstract Operations for the Memory Model
29.5.1 EventSet ( execution )
The abstract operation EventSet takes argument execution (a candidate execution ) and returns a Set
of events. It performs the following steps when called:
Let events be an empty Set.
For each Agent Events Record
aer of execution .[[EventsRecords]] , do
For each event E of aer .[[EventList]] , do
Add E to events .
Return events .
29.5.2 SharedDataBlockEventSet ( execution )
The abstract operation SharedDataBlockEventSet takes argument execution (a candidate execution ) and returns a Set
of events. It performs the following steps when called:
Let events be an empty Set.
For each event E of EventSet (execution ), do
If E is a ReadSharedMemory ,
WriteSharedMemory ,
or ReadModifyWriteSharedMemory
event, add E to events .
Return events .
29.5.3 HostEventSet ( execution )
The abstract operation HostEventSet takes argument execution (a candidate execution ) and returns a Set
of events. It performs the following steps when called:
Let events be an empty Set.
For each event E of EventSet (execution ), do
If E is not in SharedDataBlockEventSet (execution ),
add E to events .
Return events .
29.5.4 ComposeWriteEventBytes ( execution ,
byteIndex , Ws )
The abstract operation ComposeWriteEventBytes takes arguments execution (a candidate execution ),
byteIndex (a non-negative integer ), and Ws (a List of either WriteSharedMemory or ReadModifyWriteSharedMemory events)
and returns a List of byte
values . It performs the following steps when called:
Let byteLocation be byteIndex .
Let bytesRead be a new empty List .
For each element W of Ws , do
Assert : W has
byteLocation in its range.
Let payloadIndex be byteLocation - W .[[ByteIndex]] .
If W is a WriteSharedMemory
event, then
Let byte be W .[[Payload]] [payloadIndex ].
Else,
Assert : W is a
ReadModifyWriteSharedMemory
event.
Let bytes be ValueOfReadEvent (execution ,
W ).
Let bytesModified be W .[[ModifyOp]] (bytes , W .[[Payload]] ).
Let byte be
bytesModified [payloadIndex ].
Append byte to bytesRead .
Set byteLocation to byteLocation + 1.
Return bytesRead .
Note 1
The read-modify-write modification [[ModifyOp]] is given by the
function properties on the Atomics object that introduce ReadModifyWriteSharedMemory
events.
Note 2
This abstract operation composes a List of write
events into a List of byte
values . It is used in the event semantics of ReadSharedMemory and
ReadModifyWriteSharedMemory
events.
29.5.5 ValueOfReadEvent ( execution , R )
The abstract operation ValueOfReadEvent takes arguments execution (a candidate execution ) and R (a
ReadSharedMemory or ReadModifyWriteSharedMemory event)
and returns a List of byte
values . It performs the following steps when called:
Let Ws be reads-bytes-from (R ) in
execution .
Assert :
Ws is a List of WriteSharedMemory or
ReadModifyWriteSharedMemory
events with length equal to R .[[ElementSize]] .
Return ComposeWriteEventBytes (execution ,
R .[[ByteIndex]] , Ws ).
29.6 Relations of Candidate Executions
The following relations and mathematical functions are parameterized over a particular candidate
execution and order its events.
29.6.1 is-agent-order-before
For a candidate execution
execution , its is-agent-order-before Relation is the least
Relation on events that satisfies the following.
For events E and D , E is-agent-order-before D in
execution if there is some Agent Events Record
aer in execution .[[EventsRecords]] such that
aer .[[EventList]] contains both E and
D and E is before D in List order of
aer .[[EventList]] .
Note
Each agent
introduces events in a per-agent strict total
order during the evaluation. This is the union of those strict total
orders .
29.6.2 reads-bytes-from
For a candidate execution
execution , its reads-bytes-from function is a mathematical function mapping
events in SharedDataBlockEventSet (execution )
to Lists of events in
SharedDataBlockEventSet (execution )
that satisfies the following conditions.
A candidate execution always admits a
reads-bytes-from function.
29.6.3 reads-from
For a candidate execution
execution , its reads-from Relation is the least
Relation on events that satisfies the following.
29.6.4 host-synchronizes-with
For a candidate execution
execution , its host-synchronizes-with Relation is a host -provided strict partial order on
host -specific events that
satisfies at least the following.
If E host-synchronizes-with D in execution , HostEventSet (execution ) contains
E and D .
There is no cycle in the union of host-synchronizes-with and is-agent-order-before in
execution .
Note 1
For two host -specific events E and D
in a candidate execution
execution , E host-synchronizes-with D in
execution implies E happens-before
D in execution .
Note 2
This Relation allows
the host to
provide additional synchronization mechanisms, such as postMessage between
HTML workers.
29.6.5 synchronizes-with
For a candidate execution
execution , its synchronizes-with Relation is the least
Relation on events that satisfies the following.
For events R and W , W synchronizes-with R in
execution if R reads-from W in
execution , R .[[Order]] is
seq-cst , W .[[Order]] is
seq-cst , and R and W have equal ranges.
For each element eventsRecord of execution .[[EventsRecords]] , the following is true.
For events S and Sw , S synchronizes-with
Sw in execution if eventsRecord .[[AgentSynchronizesWith]] contains (S ,
Sw ).
For events E and D , E synchronizes-with D in
execution if execution .[[HostSynchronizesWith]] contains (E , D ).
Note 1
Owing to convention in memory model literature, in a candidate execution
execution , write events synchronizes-with read events, instead of read events
synchronizes-with write events.
Note 2
In a candidate execution
execution , init events do not participate in this
Relation and are
instead constrained directly by happens-before .
Note 3
In a candidate execution
execution , not all seq-cst events related by reads-from are related by
synchronizes-with. Only events that also have equal ranges are related by
synchronizes-with.
Note 4
For Shared Data Block events
R and W in a candidate
execution execution such that W
synchronizes-with R , R may reads-from other writes
than W .
29.6.6 happens-before
For a candidate execution
execution , its happens-before Relation is the least
Relation on events that satisfies the following.
Note
Because happens-before is a superset of agent -order, a candidate execution is
consistent with the single-thread evaluation semantics of ECMAScript.
29.7 Properties of Valid Executions
29.7.1 Valid Chosen Reads
A candidate execution execution
has valid chosen reads if the following algorithm returns true .
For each ReadSharedMemory or
ReadModifyWriteSharedMemory
event R of SharedDataBlockEventSet (execution ),
do
Let chosenValueRecord be the element of execution .[[ChosenValues]] whose [[Event]] field is R .
Let chosenValue be chosenValueRecord .[[ChosenValue]] .
Let readValue be ValueOfReadEvent (execution ,
R ).
Let chosenLen be the number of elements in chosenValue .
Let readLen be the number of elements in readValue .
If chosenLen ≠ readLen , then
Return false .
If chosenValue [i ] ≠ readValue [i ] for
some integer i in the interval
from 0 (inclusive) to chosenLen (exclusive), then
Return false .
Return true .
29.7.2 Coherent Reads
A candidate execution execution
has coherent reads if the following algorithm returns true .
For each ReadSharedMemory or
ReadModifyWriteSharedMemory
event R of SharedDataBlockEventSet (execution ),
do
Let Ws be reads-bytes-from (R )
in execution .
Let byteLocation be R .[[ByteIndex]] .
For each element W of Ws , do
If R happens-before
W in execution , then
Return false .
If there exists a WriteSharedMemory
or ReadModifyWriteSharedMemory
event V that has byteLocation in its range such
that W happens-before
V in execution and V happens-before
R in execution , then
Return false .
Set byteLocation to byteLocation + 1.
Return true .
29.7.3 Tear Free Reads
A candidate execution execution
has tear free reads if the following algorithm returns true .
For each ReadSharedMemory or
ReadModifyWriteSharedMemory
event R of SharedDataBlockEventSet (execution ),
do
If R .[[NoTear]] is true ,
then
Assert : The remainder of dividing
R .[[ByteIndex]] by R .[[ElementSize]] is 0.
For each event W such that R reads-from W in
execution and W .[[NoTear]] is true , do
If R and W have equal ranges and there
exists an event V such that V and
W have equal ranges, V .[[NoTear]] is true ,
W and V are not the same Shared Data Block
event , and R reads-from
V in execution , then
Return false .
Return true .
Note
An event's [[NoTear]] field is true when that
event was introduced via accessing an integer TypedArray , and
false when introduced via accessing a floating point TypedArray
or DataView.
Intuitively, this requirement says when a memory range is accessed in an aligned fashion
via an integer TypedArray , a single write
event on that range must "win" when in a data race with other write
events with equal ranges. More precisely, this requirement says an aligned read event
cannot read a value composed of bytes from multiple, different write events all with
equal ranges. It is possible, however, for an aligned read event to read from multiple
write events with overlapping ranges.
29.7.4 Sequentially Consistent Atomics
For a candidate execution
execution , is-memory-order-before is a strict total order of all
events in EventSet (execution ) that satisfies the
following.
A candidate execution has sequentially
consistent atomics if it admits an is-memory-order-before Relation .
Note 3
While is-memory-order-before includes all events in EventSet (execution ), those that
are not constrained by happens-before or synchronizes-with in
execution are allowed to occur anywhere in the order.
29.7.5 Valid Executions
A candidate execution execution
is a valid execution (or simply an execution) if all of the following are true.
All programs have at least one valid execution.
29.8 Races
For an execution execution and events E and D that are contained in
SharedDataBlockEventSet (execution ),
E and D are in a race if the following algorithm returns
true .
If E and D are not the same Shared Data Block event , then
If it is not the case that both E happens-before
D in execution and D happens-before E in
execution , then
If E and D are both WriteSharedMemory
or ReadModifyWriteSharedMemory
events and E and D do not have disjoint ranges, then
Return true .
If E reads-from D in
execution or D reads-from
E in execution , then
Return true .
Return false .
29.9 Data Races
For an execution execution and events E and D that are contained in
SharedDataBlockEventSet (execution ),
E and D are in a data race if the following algorithm
returns true .
If E and D are in a race in execution , then
If E .[[Order]] is not
seq-cst or D .[[Order]] is
not seq-cst , then
Return true .
If E and D have overlapping ranges, then
Return true .
Return false .
29.10 Data Race Freedom
An execution execution is data race free if there are no two
events in SharedDataBlockEventSet (execution )
that are in a data
race .
A program is data race free if all its executions are data race free.
The memory
model guarantees sequential consistency of all events for data race free
programs.
29.11 Shared Memory Guidelines
Note 1
The following are guidelines for ECMAScript programmers working with shared memory.
We recommend programs be kept data race free , i.e., make it so that
it is impossible for there to be concurrent non-atomic operations on the same memory
location. Data race free programs have
interleaving semantics where each step in the evaluation semantics of each agent are interleaved with
each other. For data race free programs, it is not
necessary to understand the details of the memory model . The details are
unlikely to build intuition that will help one to better write ECMAScript.
More generally, even if a program is not data race free it may
have predictable behaviour, so long as atomic operations are not involved in any data races
and the operations that race all have the same access size. The simplest way to arrange for
atomics not to be involved in races is to ensure that different memory cells are used by
atomic and non-atomic operations and that atomic accesses of different sizes are not used to
access the same cells at the same time. Effectively, the program should treat shared memory
as strongly typed as much as possible. One still cannot depend on the ordering and timing of
non-atomic accesses that race, but if memory is treated as strongly typed the racing
accesses will not "tear" (bits of their values will not be mixed).
Note 2
The following are guidelines for ECMAScript implementers writing compiler transformations for
programs using shared memory.
It is desirable to allow most program transformations that are valid in a single-agent setting in a
multi-agent setting,
to ensure that the performance of each agent in a multi-agent program is as good as it would be
in a single-agent
setting. Frequently these transformations are hard to judge. We outline some rules about
program transformations that are intended to be taken as normative (in that they are implied
by the memory
model or stronger than what the memory model implies) but
which are likely not exhaustive. These rules are intended to apply to program
transformations that precede the introductions of the events that make up the is-agent-order-before Relation .
Let an agent-order slice be the subset
of the is-agent-order-before Relation pertaining
to a single agent .
Let possible read values of a read event be the set of all values of
ValueOfReadEvent for that event across
all valid executions.
Any transformation of an agent-order slice that is valid in the absence of shared memory is
valid in the presence of shared memory, with the following exceptions.
Atomics are carved in stone : Program transformations must not cause the
seq-cst events in an agent-order slice to be reordered with
its unordered operations, nor its
seq-cst operations to be reordered with each other, nor may a
program transformation remove a seq-cst operation from the
is-agent-order-before Relation .
(In practice, the prohibition on reorderings forces a compiler to assume that every
seq-cst operation is a synchronization and included in the
final is-memory-order-before Relation ,
which it would usually have to assume anyway in the absence of inter-agent program
analysis. It also forces the compiler to assume that every call where the callee's
effects on the memory-order are unknown may contain seq-cst
operations.)
Reads must be stable : Any given shared memory read must only observe a
single value in an execution.
(For example, if what is semantically a single read in the program is executed
multiple times then the program is subsequently allowed to observe only one of the
values read. A transformation known as rematerialization can violate this rule.)
Writes must be stable : All observable writes to shared memory must follow
from program semantics in an execution.
(For example, a transformation may not introduce certain observable writes, such as
by using read-modify-write operations on a larger location to write a smaller datum,
writing a value to memory that the program could not have written, or writing a
just-read value back to the location it was read from, if that location could have
been overwritten by another agent after the read.)
Possible read values must be non-empty : Program transformations cannot cause
the possible read values of a shared memory read to become empty.
(Counterintuitively, this rule in effect restricts transformations on writes, because
writes have force in memory model insofar as to be read
by read events. For example, writes may be moved and coalesced and sometimes
reordered between two seq-cst operations, but the
transformation may not remove every write that updates a location; some write must
be preserved.)
Examples of transformations that remain valid are: merging multiple non-atomic reads from the
same location, reordering non-atomic reads, introducing speculative non-atomic reads,
merging multiple non-atomic writes to the same location, reordering non-atomic writes to
different locations, and hoisting non-atomic reads out of loops even if that affects
termination. Note in general that aliased TypedArrays make it hard to prove that locations
are different.
Note 3
The following are guidelines for ECMAScript implementers generating machine code for shared
memory accesses.
For architectures with memory models no weaker than those of ARM or Power, non-atomic stores
and loads may be compiled to bare stores and loads on the target architecture. Atomic stores
and loads may be compiled down to instructions that guarantee sequential consistency. If no
such instructions exist, memory barriers are to be employed, such as placing barriers on
both sides of a bare store or load. Read-modify-write operations may be compiled to
read-modify-write instructions on the target architecture, such as
LOCK-prefixed instructions on x86, load-exclusive/store-exclusive instructions
on ARM, and load-link/store-conditional instructions on Power.
Specifically, the memory model is intended to allow code
generation as follows.
Every atomic operation in the program is assumed to be necessary.
Atomic operations are never rearranged with each other or with non-atomic operations.
Functions are always assumed to perform atomic operations.
Atomic operations are never implemented as read-modify-write operations on larger data,
but as non-lock-free atomics if the platform does not have atomic operations of the
appropriate size. (We already assume that every platform has normal memory access
operations of every interesting size.)
Naive code generation uses these patterns:
Regular loads and stores compile to single load and store instructions.
Lock-free atomic loads and stores compile to a full (sequentially consistent) fence, a
regular load or store, and a full fence.
Lock-free atomic read-modify-write accesses compile to a full fence, an atomic
read-modify-write instruction sequence, and a full fence.
Non-lock-free atomics compile to a spinlock acquire, a full fence, a series of
non-atomic load and store instructions, a full fence, and a spinlock release.
That mapping is correct so long as an atomic operation on an address range does not race with
a non-atomic write or with an atomic operation of different size. However, that is all we
need: the memory model effectively demotes the atomic
operations involved in a race to non-atomic status. On the other hand, the naive mapping is
quite strong: it allows atomic operations to be used as sequentially consistent fences,
which the memory model does not actually guarantee.
Local improvements to those basic patterns are also allowed, subject to the constraints of
the memory
model . For example:
There are obvious platform-dependent improvements that remove redundant fences. For
example, on x86 the fences around lock-free atomic loads and stores can always be
omitted except for the fence following a store, and no fence is needed for lock-free
read-modify-write instructions, as these all use LOCK-prefixed
instructions. On many platforms there are fences of several strengths, and weaker fences
can be used in certain contexts without destroying sequential consistency.
Most modern platforms support lock-free atomics for all the data sizes required by
ECMAScript atomics. Should non-lock-free atomics be needed, the fences surrounding the
body of the atomic operation can usually be folded into the lock and unlock steps. The
simplest solution for non-lock-free atomics is to have a single lock word per
SharedArrayBuffer.
There are also more complicated platform-dependent local improvements, requiring some
code analysis. For example, two back-to-back fences often have the same effect as a
single fence, so if code is generated for two atomic operations in sequence, only a
single fence need separate them. On x86, even a single fence separating atomic stores
can be omitted, as the fence following a store is only needed to separate the store from
a subsequent load.
Annex A (informative) Grammar Summary
A.1 Lexical Grammar
SourceCharacter ::
any Unicode code point
InputElementDiv ::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
RightBracePunctuator
InputElementRegExp ::
WhiteSpace
LineTerminator
Comment
CommonToken
RightBracePunctuator
RegularExpressionLiteral
InputElementRegExpOrTemplateTail
::
WhiteSpace
LineTerminator
Comment
CommonToken
RegularExpressionLiteral
TemplateSubstitutionTail
InputElementTemplateTail
::
WhiteSpace
LineTerminator
Comment
CommonToken
DivPunctuator
TemplateSubstitutionTail
InputElementHashbangOrRegExp
::
WhiteSpace
LineTerminator
Comment
CommonToken
HashbangComment
RegularExpressionLiteral
WhiteSpace ::
<TAB>
<VT>
<FF>
<ZWNBSP>
<USP>
LineTerminator ::
<LF>
<CR>
<LS>
<PS>
LineTerminatorSequence
::
<LF>
<CR>
[lookahead ≠ <LF> ]
<LS>
<PS>
<CR>
<LF>
Comment ::
MultiLineComment
SingleLineComment
MultiLineComment ::
/*
MultiLineCommentChars opt
*/
MultiLineCommentChars
::
MultiLineNotAsteriskChar
MultiLineCommentChars opt
*
PostAsteriskCommentChars opt
PostAsteriskCommentChars
::
MultiLineNotForwardSlashOrAsteriskChar
MultiLineCommentChars opt
*
PostAsteriskCommentChars opt
MultiLineNotAsteriskChar
::
SourceCharacter but not
*
MultiLineNotForwardSlashOrAsteriskChar
::
SourceCharacter but not one of
/ or *
SingleLineComment ::
//
SingleLineCommentChars opt
SingleLineCommentChars
::
SingleLineCommentChar
SingleLineCommentChars opt
SingleLineCommentChar
::
SourceCharacter but not
LineTerminator
HashbangComment ::
#!
SingleLineCommentChars opt
CommonToken ::
IdentifierName
PrivateIdentifier
Punctuator
NumericLiteral
StringLiteral
Template
PrivateIdentifier ::
#
IdentifierName
IdentifierName ::
IdentifierStart
IdentifierName
IdentifierPart
IdentifierStart ::
IdentifierStartChar
\
UnicodeEscapeSequence
IdentifierPart ::
IdentifierPartChar
\
UnicodeEscapeSequence
IdentifierStartChar ::
UnicodeIDStart
$
_
IdentifierPartChar ::
UnicodeIDContinue
$
AsciiLetter :: one
of a b c d
e f g h i
j k l m n
o p q r s
t u v w x
y z A B C
D E F G H
I J K L M
N O P Q R
S T U V W
X Y Z
UnicodeIDStart ::
any Unicode code point with the Unicode property “ID_Start”
UnicodeIDContinue ::
any Unicode code point with the Unicode property “ID_Continue”
ReservedWord :: one
of await break case
catch class const continue
debugger default delete do
else enum export extends
false finally for function
if import in instanceof
new null return super
switch this throw true
try typeof var void
while with yield
Punctuator ::
OptionalChainingPunctuator
OtherPunctuator
OptionalChainingPunctuator
::
?.
[lookahead ∉ DecimalDigit ]
OtherPunctuator ::
one of { ( )
[ ] . ... ;
, < > <=
>= == != === !==
+ - * % **
++ -- << >>
>>> & | ^
! ~ && || ??
? : = += -=
*= %= **= <<=
>>= >>>= &= |=
^= &&= ||= ??=
=>
DivPunctuator ::
/
/=
RightBracePunctuator ::
}
NullLiteral ::
null
BooleanLiteral ::
true
false
NumericLiteralSeparator
::
_
NumericLiteral ::
DecimalLiteral
DecimalBigIntegerLiteral
NonDecimalIntegerLiteral [+Sep]
NonDecimalIntegerLiteral [+Sep]
BigIntLiteralSuffix
LegacyOctalIntegerLiteral
DecimalBigIntegerLiteral
::
0
BigIntLiteralSuffix
NonZeroDigit
DecimalDigits [+Sep] opt
BigIntLiteralSuffix
NonZeroDigit
NumericLiteralSeparator
DecimalDigits [+Sep]
BigIntLiteralSuffix
NonDecimalIntegerLiteral [Sep]
::
BinaryIntegerLiteral [?Sep]
OctalIntegerLiteral [?Sep]
HexIntegerLiteral [?Sep]
BigIntLiteralSuffix ::
n
DecimalLiteral ::
DecimalIntegerLiteral
.
DecimalDigits [+Sep] opt
ExponentPart [+Sep] opt
.
DecimalDigits [+Sep]
ExponentPart [+Sep] opt
DecimalIntegerLiteral
ExponentPart [+Sep] opt
DecimalIntegerLiteral
::
0
NonZeroDigit
NonZeroDigit
NumericLiteralSeparator opt
DecimalDigits [+Sep]
NonOctalDecimalIntegerLiteral
DecimalDigits [Sep]
::
DecimalDigit
DecimalDigits [?Sep]
DecimalDigit
[+Sep]
DecimalDigits [+Sep]
NumericLiteralSeparator
DecimalDigit
DecimalDigit :: one
of 0 1 2 3
4 5 6 7 8
9
NonZeroDigit :: one
of 1 2 3 4
5 6 7 8 9
ExponentPart [Sep]
::
ExponentIndicator
SignedInteger [?Sep]
ExponentIndicator ::
one of e E
SignedInteger [Sep]
::
DecimalDigits [?Sep]
+
DecimalDigits [?Sep]
-
DecimalDigits [?Sep]
BinaryIntegerLiteral [Sep]
::
0b
BinaryDigits [?Sep]
0B
BinaryDigits [?Sep]
BinaryDigits [Sep]
::
BinaryDigit
BinaryDigits [?Sep]
BinaryDigit
[+Sep]
BinaryDigits [+Sep]
NumericLiteralSeparator
BinaryDigit
BinaryDigit :: one
of 0 1
OctalIntegerLiteral [Sep]
::
0o
OctalDigits [?Sep]
0O
OctalDigits [?Sep]
OctalDigits [Sep]
::
OctalDigit
OctalDigits [?Sep]
OctalDigit
[+Sep]
OctalDigits [+Sep]
NumericLiteralSeparator
OctalDigit
LegacyOctalIntegerLiteral
::
0
OctalDigit
LegacyOctalIntegerLiteral
OctalDigit
NonOctalDecimalIntegerLiteral
::
0
NonOctalDigit
LegacyOctalLikeDecimalIntegerLiteral
NonOctalDigit
NonOctalDecimalIntegerLiteral
DecimalDigit
LegacyOctalLikeDecimalIntegerLiteral
::
0
OctalDigit
LegacyOctalLikeDecimalIntegerLiteral
OctalDigit
OctalDigit :: one
of 0 1 2 3
4 5 6 7
NonOctalDigit ::
one of 8 9
HexIntegerLiteral [Sep]
::
0x
HexDigits [?Sep]
0X
HexDigits [?Sep]
HexDigits [Sep]
::
HexDigit
HexDigits [?Sep]
HexDigit
[+Sep]
HexDigits [+Sep]
NumericLiteralSeparator
HexDigit
HexDigit :: one
of 0 1 2 3
4 5 6 7 8
9 a b c d
e f A B C
D E F
StringLiteral ::
"
DoubleStringCharacters opt
"
'
SingleStringCharacters opt
'
DoubleStringCharacters
::
DoubleStringCharacter
DoubleStringCharacters opt
SingleStringCharacters
::
SingleStringCharacter
SingleStringCharacters opt
DoubleStringCharacter
::
SourceCharacter but not one of
" or \ or LineTerminator
<LS>
<PS>
\
EscapeSequence
LineContinuation
SingleStringCharacter
::
SourceCharacter but not one of
' or \ or LineTerminator
<LS>
<PS>
\
EscapeSequence
LineContinuation
LineContinuation ::
\
LineTerminatorSequence
EscapeSequence ::
CharacterEscapeSequence
0
[lookahead ∉ DecimalDigit ]
LegacyOctalEscapeSequence
NonOctalDecimalEscapeSequence
HexEscapeSequence
UnicodeEscapeSequence
CharacterEscapeSequence
::
SingleEscapeCharacter
NonEscapeCharacter
SingleEscapeCharacter
:: one of ' "
\ b f n r
t v
NonEscapeCharacter ::
SourceCharacter but not one of
EscapeCharacter or LineTerminator
EscapeCharacter ::
SingleEscapeCharacter
DecimalDigit
x
u
LegacyOctalEscapeSequence
::
0
[lookahead ∈ { 8 , 9 }]
NonZeroOctalDigit
[lookahead ∉ OctalDigit ]
ZeroToThree
OctalDigit
[lookahead ∉ OctalDigit ]
FourToSeven
OctalDigit
ZeroToThree
OctalDigit
OctalDigit
NonZeroOctalDigit ::
OctalDigit but not
0
ZeroToThree :: one
of 0 1 2
3
FourToSeven :: one
of 4 5 6
7
NonOctalDecimalEscapeSequence
:: one of 8
9
HexEscapeSequence ::
x
HexDigit
HexDigit
UnicodeEscapeSequence
::
u
Hex4Digits
u{
CodePoint
}
Hex4Digits ::
HexDigit
HexDigit
HexDigit
HexDigit
RegularExpressionLiteral
::
/
RegularExpressionBody
/
RegularExpressionFlags
RegularExpressionBody
::
RegularExpressionFirstChar
RegularExpressionChars
RegularExpressionChars
::
[empty]
RegularExpressionChars
RegularExpressionChar
RegularExpressionFirstChar
::
RegularExpressionNonTerminator
but not one of * or \ or / or
[
RegularExpressionBackslashSequence
RegularExpressionClass
RegularExpressionChar
::
RegularExpressionNonTerminator
but not one of \ or / or [
RegularExpressionBackslashSequence
RegularExpressionClass
RegularExpressionBackslashSequence
::
\
RegularExpressionNonTerminator
RegularExpressionNonTerminator
::
SourceCharacter but not
LineTerminator
RegularExpressionClass
::
[
RegularExpressionClassChars
]
RegularExpressionClassChars
::
[empty]
RegularExpressionClassChars
RegularExpressionClassChar
RegularExpressionClassChar
::
RegularExpressionNonTerminator
but not one of ] or \
RegularExpressionBackslashSequence
RegularExpressionFlags
::
[empty]
RegularExpressionFlags
IdentifierPartChar
Template ::
NoSubstitutionTemplate
TemplateHead
NoSubstitutionTemplate
::
`
TemplateCharacters opt
`
TemplateHead ::
`
TemplateCharacters opt
${
TemplateSubstitutionTail
::
TemplateMiddle
TemplateTail
TemplateMiddle ::
}
TemplateCharacters opt
${
TemplateTail ::
}
TemplateCharacters opt
`
TemplateCharacters ::
TemplateCharacter
TemplateCharacters opt
TemplateCharacter ::
$
[lookahead ≠ { ]
\
TemplateEscapeSequence
\
NotEscapeSequence
LineContinuation
LineTerminatorSequence
SourceCharacter but not one of
` or \ or $ or LineTerminator
TemplateEscapeSequence
::
CharacterEscapeSequence
0
[lookahead ∉ DecimalDigit ]
HexEscapeSequence
UnicodeEscapeSequence
NotEscapeSequence ::
0
DecimalDigit
DecimalDigit but not
0
x
[lookahead ∉ HexDigit ]
x
HexDigit
[lookahead ∉ HexDigit ]
u
[lookahead ∉ HexDigit ]
[lookahead ≠ { ]
u
HexDigit
[lookahead ∉ HexDigit ]
u
HexDigit
HexDigit
[lookahead ∉ HexDigit ]
u
HexDigit
HexDigit
HexDigit
[lookahead ∉ HexDigit ]
u
{
[lookahead ∉ HexDigit ]
u
{
NotCodePoint
[lookahead ∉ HexDigit ]
u
{
CodePoint
[lookahead ∉ HexDigit ]
[lookahead ≠ } ]
NotCodePoint ::
HexDigits [~Sep]
but only if the MV of HexDigits >
0x10FFFF
CodePoint ::
HexDigits [~Sep]
but only if the MV of HexDigits ≤
0x10FFFF
A.2 Expressions
IdentifierReference [Yield,
Await] :
Identifier
[~Yield]
yield
[~Await]
await
BindingIdentifier [Yield,
Await] :
Identifier
yield
await
LabelIdentifier [Yield,
Await] :
Identifier
[~Yield]
yield
[~Await]
await
Identifier :
IdentifierName but not ReservedWord
PrimaryExpression [Yield,
Await] :
this
IdentifierReference [?Yield,
?Await]
Literal
ArrayLiteral [?Yield,
?Await]
ObjectLiteral [?Yield,
?Await]
FunctionExpression
ClassExpression [?Yield,
?Await]
GeneratorExpression
AsyncFunctionExpression
AsyncGeneratorExpression
RegularExpressionLiteral
TemplateLiteral [?Yield, ?Await,
~Tagged]
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList [Yield,
Await] :
(
Expression [+In, ?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
)
(
)
(
...
BindingIdentifier [?Yield,
?Await]
)
(
...
BindingPattern [?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
...
BindingIdentifier [?Yield,
?Await]
)
(
Expression [+In, ?Yield,
?Await]
,
...
BindingPattern [?Yield,
?Await]
)
When processing an instance of the production
PrimaryExpression [Yield,
Await] :
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
the interpretation of CoverParenthesizedExpressionAndArrowParameterList
is refined using the following grammar:
ParenthesizedExpression [Yield,
Await] :
(
Expression [+In, ?Yield,
?Await]
)
Literal :
NullLiteral
BooleanLiteral
NumericLiteral
StringLiteral
ArrayLiteral [Yield,
Await] :
[
Elision opt
]
[
ElementList [?Yield,
?Await]
]
[
ElementList [?Yield,
?Await]
,
Elision opt
]
ElementList [Yield,
Await] :
Elision opt
AssignmentExpression [+In,
?Yield, ?Await]
Elision opt
SpreadElement [?Yield,
?Await]
ElementList [?Yield,
?Await]
,
Elision opt
AssignmentExpression [+In,
?Yield, ?Await]
ElementList [?Yield,
?Await]
,
Elision opt
SpreadElement [?Yield,
?Await]
Elision :
,
Elision
,
SpreadElement [Yield,
Await] :
...
AssignmentExpression [+In,
?Yield, ?Await]
ObjectLiteral [Yield,
Await] :
{
}
{
PropertyDefinitionList [?Yield,
?Await]
}
{
PropertyDefinitionList [?Yield,
?Await]
,
}
PropertyDefinitionList [Yield,
Await] :
PropertyDefinition [?Yield,
?Await]
PropertyDefinitionList [?Yield,
?Await]
,
PropertyDefinition [?Yield,
?Await]
PropertyDefinition [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
CoverInitializedName [?Yield,
?Await]
PropertyName [?Yield,
?Await]
:
AssignmentExpression [+In,
?Yield, ?Await]
MethodDefinition [?Yield,
?Await]
...
AssignmentExpression [+In,
?Yield, ?Await]
PropertyName [Yield,
Await] :
LiteralPropertyName
ComputedPropertyName [?Yield,
?Await]
LiteralPropertyName :
IdentifierName
StringLiteral
NumericLiteral
ComputedPropertyName [Yield,
Await] :
[
AssignmentExpression [+In,
?Yield, ?Await]
]
CoverInitializedName [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await]
Initializer [In, Yield,
Await] :
=
AssignmentExpression [?In,
?Yield, ?Await]
TemplateLiteral [Yield, Await,
Tagged] :
NoSubstitutionTemplate
SubstitutionTemplate [?Yield,
?Await, ?Tagged]
SubstitutionTemplate [Yield,
Await, Tagged] :
TemplateHead
Expression [+In, ?Yield,
?Await]
TemplateSpans [?Yield, ?Await,
?Tagged]
TemplateSpans [Yield, Await,
Tagged] :
TemplateTail
TemplateMiddleList [?Yield,
?Await, ?Tagged]
TemplateTail
TemplateMiddleList [Yield, Await,
Tagged] :
TemplateMiddle
Expression [+In, ?Yield,
?Await]
TemplateMiddleList [?Yield,
?Await, ?Tagged]
TemplateMiddle
Expression [+In, ?Yield,
?Await]
MemberExpression [Yield,
Await] :
PrimaryExpression [?Yield,
?Await]
MemberExpression [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
MemberExpression [?Yield,
?Await]
.
IdentifierName
MemberExpression [?Yield,
?Await]
TemplateLiteral [?Yield, ?Await,
+Tagged]
SuperProperty [?Yield,
?Await]
MetaProperty
new
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
MemberExpression [?Yield,
?Await]
.
PrivateIdentifier
SuperProperty [Yield,
Await] :
super
[
Expression [+In, ?Yield,
?Await]
]
super
.
IdentifierName
MetaProperty :
NewTarget
ImportMeta
NewTarget :
new
.
target
ImportMeta :
import
.
meta
NewExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
new
NewExpression [?Yield,
?Await]
CallExpression [Yield,
Await] :
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
SuperCall [?Yield,
?Await]
ImportCall [?Yield,
?Await]
CallExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
CallExpression [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
CallExpression [?Yield,
?Await]
.
IdentifierName
CallExpression [?Yield,
?Await]
TemplateLiteral [?Yield, ?Await,
+Tagged]
CallExpression [?Yield,
?Await]
.
PrivateIdentifier
When processing an instance of the production
CallExpression [Yield,
Await] :
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
the interpretation of CoverCallExpressionAndAsyncArrowHead
is refined using the following grammar:
CallMemberExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
SuperCall [Yield,
Await] :
super
Arguments [?Yield,
?Await]
ImportCall [Yield,
Await] :
import
(
AssignmentExpression [+In,
?Yield, ?Await]
,opt
)
import
(
AssignmentExpression [+In,
?Yield, ?Await]
,
AssignmentExpression [+In,
?Yield, ?Await]
,opt
)
Arguments [Yield,
Await] :
(
)
(
ArgumentList [?Yield,
?Await]
)
(
ArgumentList [?Yield,
?Await]
,
)
ArgumentList [Yield,
Await] :
AssignmentExpression [+In,
?Yield, ?Await]
...
AssignmentExpression [+In,
?Yield, ?Await]
ArgumentList [?Yield,
?Await]
,
AssignmentExpression [+In,
?Yield, ?Await]
ArgumentList [?Yield,
?Await]
,
...
AssignmentExpression [+In,
?Yield, ?Await]
OptionalExpression [Yield,
Await] :
MemberExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
CallExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
OptionalExpression [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
OptionalChain [Yield,
Await] :
?.
Arguments [?Yield,
?Await]
?.
[
Expression [+In, ?Yield,
?Await]
]
?.
IdentifierName
?.
TemplateLiteral [?Yield, ?Await,
+Tagged]
?.
PrivateIdentifier
OptionalChain [?Yield,
?Await]
Arguments [?Yield,
?Await]
OptionalChain [?Yield,
?Await]
[
Expression [+In, ?Yield,
?Await]
]
OptionalChain [?Yield,
?Await]
.
IdentifierName
OptionalChain [?Yield,
?Await]
TemplateLiteral [?Yield, ?Await,
+Tagged]
OptionalChain [?Yield,
?Await]
.
PrivateIdentifier
LeftHandSideExpression [Yield,
Await] :
NewExpression [?Yield,
?Await]
CallExpression [?Yield,
?Await]
OptionalExpression [?Yield,
?Await]
UpdateExpression [Yield,
Await] :
LeftHandSideExpression [?Yield,
?Await]
LeftHandSideExpression [?Yield,
?Await]
[no LineTerminator
here]
++
LeftHandSideExpression [?Yield,
?Await]
[no LineTerminator
here]
--
++
UnaryExpression [?Yield,
?Await]
--
UnaryExpression [?Yield,
?Await]
UnaryExpression [Yield,
Await] :
UpdateExpression [?Yield,
?Await]
delete
UnaryExpression [?Yield,
?Await]
void
UnaryExpression [?Yield,
?Await]
typeof
UnaryExpression [?Yield,
?Await]
+
UnaryExpression [?Yield,
?Await]
-
UnaryExpression [?Yield,
?Await]
~
UnaryExpression [?Yield,
?Await]
!
UnaryExpression [?Yield,
?Await]
[+Await]
AwaitExpression [?Yield]
ExponentiationExpression [Yield,
Await] :
UnaryExpression [?Yield,
?Await]
UpdateExpression [?Yield,
?Await]
**
ExponentiationExpression [?Yield,
?Await]
MultiplicativeExpression [Yield,
Await] :
ExponentiationExpression [?Yield,
?Await]
MultiplicativeExpression [?Yield,
?Await]
MultiplicativeOperator
ExponentiationExpression [?Yield,
?Await]
MultiplicativeOperator
: one of * /
%
AdditiveExpression [Yield,
Await] :
MultiplicativeExpression [?Yield,
?Await]
AdditiveExpression [?Yield,
?Await]
+
MultiplicativeExpression [?Yield,
?Await]
AdditiveExpression [?Yield,
?Await]
-
MultiplicativeExpression [?Yield,
?Await]
ShiftExpression [Yield,
Await] :
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
<<
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
>>
AdditiveExpression [?Yield,
?Await]
ShiftExpression [?Yield,
?Await]
>>>
AdditiveExpression [?Yield,
?Await]
RelationalExpression [In, Yield,
Await] :
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
<
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
>
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
<=
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
>=
ShiftExpression [?Yield,
?Await]
RelationalExpression [?In,
?Yield, ?Await]
instanceof
ShiftExpression [?Yield,
?Await]
[+In]
RelationalExpression [+In,
?Yield, ?Await]
in
ShiftExpression [?Yield,
?Await]
[+In]
PrivateIdentifier
in
ShiftExpression [?Yield,
?Await]
EqualityExpression [In, Yield,
Await] :
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
==
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
!=
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
===
RelationalExpression [?In,
?Yield, ?Await]
EqualityExpression [?In,
?Yield, ?Await]
!==
RelationalExpression [?In,
?Yield, ?Await]
BitwiseANDExpression [In, Yield,
Await] :
EqualityExpression [?In,
?Yield, ?Await]
BitwiseANDExpression [?In,
?Yield, ?Await]
&
EqualityExpression [?In,
?Yield, ?Await]
BitwiseXORExpression [In, Yield,
Await] :
BitwiseANDExpression [?In,
?Yield, ?Await]
BitwiseXORExpression [?In,
?Yield, ?Await]
^
BitwiseANDExpression [?In,
?Yield, ?Await]
BitwiseORExpression [In, Yield,
Await] :
BitwiseXORExpression [?In,
?Yield, ?Await]
BitwiseORExpression [?In,
?Yield, ?Await]
|
BitwiseXORExpression [?In,
?Yield, ?Await]
LogicalANDExpression [In, Yield,
Await] :
BitwiseORExpression [?In,
?Yield, ?Await]
LogicalANDExpression [?In,
?Yield, ?Await]
&&
BitwiseORExpression [?In,
?Yield, ?Await]
LogicalORExpression [In, Yield,
Await] :
LogicalANDExpression [?In,
?Yield, ?Await]
LogicalORExpression [?In,
?Yield, ?Await]
||
LogicalANDExpression [?In,
?Yield, ?Await]
CoalesceExpression [In, Yield,
Await] :
CoalesceExpressionHead [?In,
?Yield, ?Await]
??
BitwiseORExpression [?In,
?Yield, ?Await]
CoalesceExpressionHead [In,
Yield, Await] :
CoalesceExpression [?In,
?Yield, ?Await]
BitwiseORExpression [?In,
?Yield, ?Await]
ShortCircuitExpression [In,
Yield, Await] :
LogicalORExpression [?In,
?Yield, ?Await]
CoalesceExpression [?In,
?Yield, ?Await]
ConditionalExpression [In,
Yield, Await] :
ShortCircuitExpression [?In,
?Yield, ?Await]
ShortCircuitExpression [?In,
?Yield, ?Await]
?
AssignmentExpression [+In,
?Yield, ?Await]
:
AssignmentExpression [?In,
?Yield, ?Await]
AssignmentExpression [In, Yield,
Await] :
ConditionalExpression [?In,
?Yield, ?Await]
[+Yield]
YieldExpression [?In,
?Await]
ArrowFunction [?In, ?Yield,
?Await]
AsyncArrowFunction [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
AssignmentOperator
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
&&=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
||=
AssignmentExpression [?In,
?Yield, ?Await]
LeftHandSideExpression [?Yield,
?Await]
??=
AssignmentExpression [?In,
?Yield, ?Await]
AssignmentOperator :
one of *= /= %=
+= -= <<= >>=
>>>= &= ^= |=
**=
In certain circumstances when processing an instance of the production
AssignmentExpression [In,
Yield, Await] :
LeftHandSideExpression [?Yield,
?Await]
=
AssignmentExpression [?In,
?Yield, ?Await]
the interpretation of LeftHandSideExpression is refined using the
following grammar:
AssignmentPattern [Yield,
Await] :
ObjectAssignmentPattern [?Yield,
?Await]
ArrayAssignmentPattern [?Yield,
?Await]
ObjectAssignmentPattern [Yield,
Await] :
{
}
{
AssignmentRestProperty [?Yield,
?Await]
}
{
AssignmentPropertyList [?Yield,
?Await]
}
{
AssignmentPropertyList [?Yield,
?Await]
,
AssignmentRestProperty [?Yield,
?Await] opt
}
ArrayAssignmentPattern [Yield,
Await] :
[
Elision opt
AssignmentRestElement [?Yield,
?Await] opt
]
[
AssignmentElementList [?Yield,
?Await]
]
[
AssignmentElementList [?Yield,
?Await]
,
Elision opt
AssignmentRestElement [?Yield,
?Await] opt
]
AssignmentRestProperty [Yield,
Await] :
...
DestructuringAssignmentTarget [?Yield,
?Await]
AssignmentPropertyList [Yield,
Await] :
AssignmentProperty [?Yield,
?Await]
AssignmentPropertyList [?Yield,
?Await]
,
AssignmentProperty [?Yield,
?Await]
AssignmentElementList [Yield,
Await] :
AssignmentElisionElement [?Yield,
?Await]
AssignmentElementList [?Yield,
?Await]
,
AssignmentElisionElement [?Yield,
?Await]
AssignmentElisionElement [Yield,
Await] :
Elision opt
AssignmentElement [?Yield,
?Await]
AssignmentProperty [Yield,
Await] :
IdentifierReference [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
PropertyName [?Yield,
?Await]
:
AssignmentElement [?Yield,
?Await]
AssignmentElement [Yield,
Await] :
DestructuringAssignmentTarget [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
AssignmentRestElement [Yield,
Await] :
...
DestructuringAssignmentTarget [?Yield,
?Await]
DestructuringAssignmentTarget [Yield,
Await] :
LeftHandSideExpression [?Yield,
?Await]
Expression [In, Yield,
Await] :
AssignmentExpression [?In,
?Yield, ?Await]
Expression [?In, ?Yield,
?Await]
,
AssignmentExpression [?In,
?Yield, ?Await]
A.3 Statements
Statement [Yield, Await,
Return] :
BlockStatement [?Yield, ?Await,
?Return]
VariableStatement [?Yield,
?Await]
EmptyStatement
ExpressionStatement [?Yield,
?Await]
IfStatement [?Yield, ?Await,
?Return]
BreakableStatement [?Yield,
?Await, ?Return]
ContinueStatement [?Yield,
?Await]
BreakStatement [?Yield,
?Await]
[+Return]
ReturnStatement [?Yield,
?Await]
WithStatement [?Yield, ?Await,
?Return]
LabelledStatement [?Yield,
?Await, ?Return]
ThrowStatement [?Yield,
?Await]
TryStatement [?Yield, ?Await,
?Return]
DebuggerStatement
Declaration [Yield,
Await] :
HoistableDeclaration [?Yield,
?Await, ~Default]
ClassDeclaration [?Yield, ?Await,
~Default]
LexicalDeclaration [+In,
?Yield, ?Await]
HoistableDeclaration [Yield,
Await, Default] :
FunctionDeclaration [?Yield,
?Await, ?Default]
GeneratorDeclaration [?Yield,
?Await, ?Default]
AsyncFunctionDeclaration [?Yield,
?Await, ?Default]
AsyncGeneratorDeclaration [?Yield,
?Await, ?Default]
BreakableStatement [Yield, Await,
Return] :
IterationStatement [?Yield,
?Await, ?Return]
SwitchStatement [?Yield, ?Await,
?Return]
BlockStatement [Yield, Await,
Return] :
Block [?Yield, ?Await,
?Return]
Block [Yield,
Await, Return] :
{
StatementList [?Yield, ?Await,
?Return] opt
}
StatementList [Yield, Await,
Return] :
StatementListItem [?Yield,
?Await, ?Return]
StatementList [?Yield, ?Await,
?Return]
StatementListItem [?Yield,
?Await, ?Return]
StatementListItem [Yield, Await,
Return] :
Statement [?Yield, ?Await,
?Return]
Declaration [?Yield,
?Await]
LexicalDeclaration [In, Yield,
Await] :
LetOrConst
BindingList [?In, ?Yield,
?Await]
;
LetOrConst :
let
const
BindingList [In, Yield,
Await] :
LexicalBinding [?In, ?Yield,
?Await]
BindingList [?In, ?Yield,
?Await]
,
LexicalBinding [?In, ?Yield,
?Await]
LexicalBinding [In, Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await] opt
BindingPattern [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await]
VariableStatement [Yield,
Await] :
var
VariableDeclarationList [+In,
?Yield, ?Await]
;
VariableDeclarationList [In,
Yield, Await] :
VariableDeclaration [?In,
?Yield, ?Await]
VariableDeclarationList [?In,
?Yield, ?Await]
,
VariableDeclaration [?In,
?Yield, ?Await]
VariableDeclaration [In, Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await] opt
BindingPattern [?Yield,
?Await]
Initializer [?In, ?Yield,
?Await]
BindingPattern [Yield,
Await] :
ObjectBindingPattern [?Yield,
?Await]
ArrayBindingPattern [?Yield,
?Await]
ObjectBindingPattern [Yield,
Await] :
{
}
{
BindingRestProperty [?Yield,
?Await]
}
{
BindingPropertyList [?Yield,
?Await]
}
{
BindingPropertyList [?Yield,
?Await]
,
BindingRestProperty [?Yield,
?Await] opt
}
ArrayBindingPattern [Yield,
Await] :
[
Elision opt
BindingRestElement [?Yield,
?Await] opt
]
[
BindingElementList [?Yield,
?Await]
]
[
BindingElementList [?Yield,
?Await]
,
Elision opt
BindingRestElement [?Yield,
?Await] opt
]
BindingRestProperty [Yield,
Await] :
...
BindingIdentifier [?Yield,
?Await]
BindingPropertyList [Yield,
Await] :
BindingProperty [?Yield,
?Await]
BindingPropertyList [?Yield,
?Await]
,
BindingProperty [?Yield,
?Await]
BindingElementList [Yield,
Await] :
BindingElisionElement [?Yield,
?Await]
BindingElementList [?Yield,
?Await]
,
BindingElisionElement [?Yield,
?Await]
BindingElisionElement [Yield,
Await] :
Elision opt
BindingElement [?Yield,
?Await]
BindingProperty [Yield,
Await] :
SingleNameBinding [?Yield,
?Await]
PropertyName [?Yield,
?Await]
:
BindingElement [?Yield,
?Await]
BindingElement [Yield,
Await] :
SingleNameBinding [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
SingleNameBinding [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
BindingRestElement [Yield,
Await] :
...
BindingIdentifier [?Yield,
?Await]
...
BindingPattern [?Yield,
?Await]
EmptyStatement :
;
ExpressionStatement [Yield,
Await] :
[lookahead ∉ { { , function , async
[no LineTerminator
here]
function , class , let
[ }]
Expression [+In, ?Yield,
?Await]
;
IfStatement [Yield, Await,
Return] :
if
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
else
Statement [?Yield, ?Await,
?Return]
if
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
[lookahead ≠ else ]
IterationStatement [Yield, Await,
Return] :
DoWhileStatement [?Yield, ?Await,
?Return]
WhileStatement [?Yield, ?Await,
?Return]
ForStatement [?Yield, ?Await,
?Return]
ForInOfStatement [?Yield, ?Await,
?Return]
DoWhileStatement [Yield, Await,
Return] :
do
Statement [?Yield, ?Await,
?Return]
while
(
Expression [+In, ?Yield,
?Await]
)
;
WhileStatement [Yield, Await,
Return] :
while
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
ForStatement [Yield, Await,
Return] :
for
(
[lookahead ≠ let
[ ]
Expression [~In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
for
(
var
VariableDeclarationList [~In,
?Yield, ?Await]
;
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
for
(
LexicalDeclaration [~In,
?Yield, ?Await]
Expression [+In, ?Yield,
?Await] opt
;
Expression [+In, ?Yield,
?Await] opt
)
Statement [?Yield, ?Await,
?Return]
ForInOfStatement [Yield, Await,
Return] :
for
(
[lookahead ≠ let
[ ]
LeftHandSideExpression [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
var
ForBinding [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
ForDeclaration [?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
[lookahead ∉ { let , async
of }]
LeftHandSideExpression [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
var
ForBinding [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
for
(
ForDeclaration [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
[lookahead ≠ let ]
LeftHandSideExpression [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
var
ForBinding [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
[+Await]
for
await
(
ForDeclaration [?Yield,
?Await]
of
AssignmentExpression [+In,
?Yield, ?Await]
)
Statement [?Yield, ?Await,
?Return]
ForDeclaration [Yield,
Await] :
LetOrConst
ForBinding [?Yield,
?Await]
ForBinding [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
ContinueStatement [Yield,
Await] :
continue
;
continue
[no LineTerminator
here]
LabelIdentifier [?Yield,
?Await]
;
BreakStatement [Yield,
Await] :
break
;
break
[no LineTerminator
here]
LabelIdentifier [?Yield,
?Await]
;
ReturnStatement [Yield,
Await] :
return
;
return
[no LineTerminator
here]
Expression [+In, ?Yield,
?Await]
;
WithStatement [Yield, Await,
Return] :
with
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
SwitchStatement [Yield, Await,
Return] :
switch
(
Expression [+In, ?Yield,
?Await]
)
CaseBlock [?Yield, ?Await,
?Return]
CaseBlock [Yield, Await,
Return] :
{
CaseClauses [?Yield, ?Await,
?Return] opt
}
{
CaseClauses [?Yield, ?Await,
?Return] opt
DefaultClause [?Yield, ?Await,
?Return]
CaseClauses [?Yield, ?Await,
?Return] opt
}
CaseClauses [Yield, Await,
Return] :
CaseClause [?Yield, ?Await,
?Return]
CaseClauses [?Yield, ?Await,
?Return]
CaseClause [?Yield, ?Await,
?Return]
CaseClause [Yield, Await,
Return] :
case
Expression [+In, ?Yield,
?Await]
:
StatementList [?Yield, ?Await,
?Return] opt
DefaultClause [Yield, Await,
Return] :
default
:
StatementList [?Yield, ?Await,
?Return] opt
LabelledStatement [Yield, Await,
Return] :
LabelIdentifier [?Yield,
?Await]
:
LabelledItem [?Yield, ?Await,
?Return]
LabelledItem [Yield, Await,
Return] :
Statement [?Yield, ?Await,
?Return]
FunctionDeclaration [?Yield,
?Await, ~Default]
ThrowStatement [Yield,
Await] :
throw
[no LineTerminator
here]
Expression [+In, ?Yield,
?Await]
;
TryStatement [Yield, Await,
Return] :
try
Block [?Yield, ?Await,
?Return]
Catch [?Yield, ?Await,
?Return]
try
Block [?Yield, ?Await,
?Return]
Finally [?Yield, ?Await,
?Return]
try
Block [?Yield, ?Await,
?Return]
Catch [?Yield, ?Await,
?Return]
Finally [?Yield, ?Await,
?Return]
Catch [Yield,
Await, Return] :
catch
(
CatchParameter [?Yield,
?Await]
)
Block [?Yield, ?Await,
?Return]
catch
Block [?Yield, ?Await,
?Return]
Finally [Yield, Await,
Return] :
finally
Block [?Yield, ?Await,
?Return]
CatchParameter [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
BindingPattern [?Yield,
?Await]
DebuggerStatement :
debugger
;
A.4 Functions and Classes
UniqueFormalParameters [Yield,
Await] :
FormalParameters [?Yield,
?Await]
FormalParameters [Yield,
Await] :
[empty]
FunctionRestParameter [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
,
FormalParameterList [?Yield,
?Await]
,
FunctionRestParameter [?Yield,
?Await]
FormalParameterList [Yield,
Await] :
FormalParameter [?Yield,
?Await]
FormalParameterList [?Yield,
?Await]
,
FormalParameter [?Yield,
?Await]
FunctionRestParameter [Yield,
Await] :
BindingRestElement [?Yield,
?Await]
FormalParameter [Yield,
Await] :
BindingElement [?Yield,
?Await]
FunctionDeclaration [Yield, Await,
Default] :
function
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
[+Default]
function
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
FunctionExpression :
function
BindingIdentifier [~Yield,
~Await] opt
(
FormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
FunctionBody [Yield,
Await] :
FunctionStatementList [?Yield,
?Await]
FunctionStatementList [Yield,
Await] :
StatementList [?Yield, ?Await,
+Return] opt
ArrowFunction [In, Yield,
Await] :
ArrowParameters [?Yield,
?Await]
[no LineTerminator
here]
=>
ConciseBody [?In]
ArrowParameters [Yield,
Await] :
BindingIdentifier [?Yield,
?Await]
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
ConciseBody [In]
:
[lookahead ≠ { ]
ExpressionBody [?In,
~Await]
{
FunctionBody [~Yield,
~Await]
}
ExpressionBody [In,
Await] :
AssignmentExpression [?In,
~Yield, ?Await]
When processing an instance of the production
ArrowParameters [Yield,
Await] :
CoverParenthesizedExpressionAndArrowParameterList [?Yield,
?Await]
the interpretation of CoverParenthesizedExpressionAndArrowParameterList
is refined using the following grammar:
ArrowFormalParameters [Yield,
Await] :
(
UniqueFormalParameters [?Yield,
?Await]
)
AsyncArrowFunction [In, Yield,
Await] :
async
[no LineTerminator
here]
AsyncArrowBindingIdentifier [?Yield]
[no LineTerminator
here]
=>
AsyncConciseBody [?In]
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
[no LineTerminator
here]
=>
AsyncConciseBody [?In]
AsyncConciseBody [In]
:
[lookahead ≠ { ]
ExpressionBody [?In,
+Await]
{
AsyncFunctionBody
}
AsyncArrowBindingIdentifier [Yield]
:
BindingIdentifier [?Yield,
+Await]
CoverCallExpressionAndAsyncArrowHead [Yield,
Await] :
MemberExpression [?Yield,
?Await]
Arguments [?Yield,
?Await]
When processing an instance of the production
AsyncArrowFunction [In, Yield,
Await] :
CoverCallExpressionAndAsyncArrowHead [?Yield,
?Await]
[no LineTerminator
here]
=>
AsyncConciseBody [?In]
the interpretation of CoverCallExpressionAndAsyncArrowHead
is refined using the following grammar:
AsyncArrowHead :
async
[no LineTerminator
here]
ArrowFormalParameters [~Yield,
+Await]
MethodDefinition [Yield,
Await] :
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [~Yield,
~Await]
)
{
FunctionBody [~Yield,
~Await]
}
GeneratorMethod [?Yield,
?Await]
AsyncMethod [?Yield,
?Await]
AsyncGeneratorMethod [?Yield,
?Await]
get
ClassElementName [?Yield,
?Await]
(
)
{
FunctionBody [~Yield,
~Await]
}
set
ClassElementName [?Yield,
?Await]
(
PropertySetParameterList
)
{
FunctionBody [~Yield,
~Await]
}
PropertySetParameterList
:
FormalParameter [~Yield,
~Await]
GeneratorDeclaration [Yield,
Await, Default] :
function
*
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
[+Default]
function
*
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorExpression :
function
*
BindingIdentifier [+Yield,
~Await] opt
(
FormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorMethod [Yield,
Await] :
*
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [+Yield,
~Await]
)
{
GeneratorBody
}
GeneratorBody :
FunctionBody [+Yield,
~Await]
YieldExpression [In,
Await] :
yield
yield
[no LineTerminator
here]
AssignmentExpression [?In,
+Yield, ?Await]
yield
[no LineTerminator
here]
*
AssignmentExpression [?In,
+Yield, ?Await]
AsyncGeneratorDeclaration [Yield,
Await, Default] :
async
[no LineTerminator
here]
function
*
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
[+Default]
async
[no LineTerminator
here]
function
*
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorExpression
:
async
[no LineTerminator
here]
function
*
BindingIdentifier [+Yield,
+Await] opt
(
FormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorMethod [Yield,
Await] :
async
[no LineTerminator
here]
*
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [+Yield,
+Await]
)
{
AsyncGeneratorBody
}
AsyncGeneratorBody :
FunctionBody [+Yield,
+Await]
AsyncFunctionDeclaration [Yield,
Await, Default] :
async
[no LineTerminator
here]
function
BindingIdentifier [?Yield,
?Await]
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
[+Default]
async
[no LineTerminator
here]
function
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncFunctionExpression
:
async
[no LineTerminator
here]
function
BindingIdentifier [~Yield,
+Await] opt
(
FormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncMethod [Yield,
Await] :
async
[no LineTerminator
here]
ClassElementName [?Yield,
?Await]
(
UniqueFormalParameters [~Yield,
+Await]
)
{
AsyncFunctionBody
}
AsyncFunctionBody :
FunctionBody [~Yield,
+Await]
AwaitExpression [Yield]
:
await
UnaryExpression [?Yield,
+Await]
ClassDeclaration [Yield, Await,
Default] :
class
BindingIdentifier [?Yield,
?Await]
ClassTail [?Yield,
?Await]
[+Default]
class
ClassTail [?Yield,
?Await]
ClassExpression [Yield,
Await] :
class
BindingIdentifier [?Yield,
?Await] opt
ClassTail [?Yield,
?Await]
ClassTail [Yield,
Await] :
ClassHeritage [?Yield,
?Await] opt
{
ClassBody [?Yield,
?Await] opt
}
ClassHeritage [Yield,
Await] :
extends
LeftHandSideExpression [?Yield,
?Await]
ClassBody [Yield,
Await] :
ClassElementList [?Yield,
?Await]
ClassElementList [Yield,
Await] :
ClassElement [?Yield,
?Await]
ClassElementList [?Yield,
?Await]
ClassElement [?Yield,
?Await]
ClassElement [Yield,
Await] :
MethodDefinition [?Yield,
?Await]
static
MethodDefinition [?Yield,
?Await]
FieldDefinition [?Yield,
?Await]
;
static
FieldDefinition [?Yield,
?Await]
;
ClassStaticBlock
;
FieldDefinition [Yield,
Await] :
ClassElementName [?Yield,
?Await]
Initializer [+In, ?Yield,
?Await] opt
ClassElementName [Yield,
Await] :
PropertyName [?Yield,
?Await]
PrivateIdentifier
ClassStaticBlock :
static
{
ClassStaticBlockBody
}
ClassStaticBlockBody :
ClassStaticBlockStatementList
ClassStaticBlockStatementList
:
StatementList [~Yield, +Await,
~Return] opt
A.5 Scripts and Modules
Script :
ScriptBody opt
ScriptBody :
StatementList [~Yield, ~Await,
~Return]
Module :
ModuleBody opt
ModuleBody :
ModuleItemList
ModuleItemList :
ModuleItem
ModuleItemList
ModuleItem
ModuleItem :
ImportDeclaration
ExportDeclaration
StatementListItem [~Yield,
+Await, ~Return]
ModuleExportName :
IdentifierName
StringLiteral
ImportDeclaration :
import
ImportClause
FromClause
WithClause opt
;
import
ModuleSpecifier
WithClause opt
;
ImportClause :
ImportedDefaultBinding
NameSpaceImport
NamedImports
ImportedDefaultBinding
,
NameSpaceImport
ImportedDefaultBinding
,
NamedImports
ImportedDefaultBinding
:
ImportedBinding
NameSpaceImport :
*
as
ImportedBinding
NamedImports :
{
}
{
ImportsList
}
{
ImportsList
,
}
FromClause :
from
ModuleSpecifier
ImportsList :
ImportSpecifier
ImportsList
,
ImportSpecifier
ImportSpecifier :
ImportedBinding
ModuleExportName
as
ImportedBinding
ModuleSpecifier :
StringLiteral
ImportedBinding :
BindingIdentifier [~Yield,
+Await]
WithClause :
with
{
}
with
{
WithEntries
,opt
}
WithEntries :
AttributeKey
:
StringLiteral
AttributeKey
:
StringLiteral
,
WithEntries
AttributeKey :
IdentifierName
StringLiteral
ExportDeclaration :
export
ExportFromClause
FromClause
WithClause opt
;
export
NamedExports
;
export
VariableStatement [~Yield,
+Await]
export
Declaration [~Yield,
+Await]
export
default
HoistableDeclaration [~Yield,
+Await, +Default]
export
default
ClassDeclaration [~Yield, +Await,
+Default]
export
default
[lookahead ∉ { function , async
[no LineTerminator
here]
function , class }]
AssignmentExpression [+In,
~Yield, +Await]
;
ExportFromClause :
*
*
as
ModuleExportName
NamedExports
NamedExports :
{
}
{
ExportsList
}
{
ExportsList
,
}
ExportsList :
ExportSpecifier
ExportsList
,
ExportSpecifier
ExportSpecifier :
ModuleExportName
ModuleExportName
as
ModuleExportName
A.6 Number Conversions
StringNumericLiteral
:::
StrWhiteSpace opt
StrWhiteSpace opt
StrNumericLiteral
StrWhiteSpace opt
StrWhiteSpace :::
StrWhiteSpaceChar
StrWhiteSpace opt
StrWhiteSpaceChar :::
WhiteSpace
LineTerminator
StrNumericLiteral :::
StrDecimalLiteral
NonDecimalIntegerLiteral [~Sep]
StrDecimalLiteral :::
StrUnsignedDecimalLiteral
+
StrUnsignedDecimalLiteral
-
StrUnsignedDecimalLiteral
StrUnsignedDecimalLiteral
:::
Infinity
DecimalDigits [~Sep]
.
DecimalDigits [~Sep] opt
ExponentPart [~Sep] opt
.
DecimalDigits [~Sep]
ExponentPart [~Sep] opt
DecimalDigits [~Sep]
ExponentPart [~Sep] opt
All grammar symbols not explicitly defined by the StringNumericLiteral grammar have the
definitions used in the Lexical Grammar for numeric literals .
StringIntegerLiteral
:::
StrWhiteSpace opt
StrWhiteSpace opt
StrIntegerLiteral
StrWhiteSpace opt
StrIntegerLiteral :::
SignedInteger [~Sep]
NonDecimalIntegerLiteral [~Sep]
A.7 Time Zone Offset String Format
UTCOffset :::
ASCIISign
Hour
ASCIISign
Hour
HourSubcomponents [+Extended]
ASCIISign
Hour
HourSubcomponents [~Extended]
ASCIISign ::: one
of + -
Hour :::
0
DecimalDigit
1
DecimalDigit
20
21
22
23
HourSubcomponents [Extended]
:::
TimeSeparator [?Extended]
MinuteSecond
TimeSeparator [?Extended]
MinuteSecond
TimeSeparator [?Extended]
MinuteSecond
TemporalDecimalFraction opt
TimeSeparator [Extended]
::: [+Extended]
:
[~Extended]
[empty]
MinuteSecond :::
0
DecimalDigit
1
DecimalDigit
2
DecimalDigit
3
DecimalDigit
4
DecimalDigit
5
DecimalDigit
TemporalDecimalFraction
:::
TemporalDecimalSeparator
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
DecimalDigit
TemporalDecimalSeparator
::: one of .
,
A.8 Regular Expressions
Pattern [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Disjunction [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
|
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Alternative [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
[empty]
Alternative [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Term [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Term [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
Assertion [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
Atom [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Atom [?UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Quantifier
Assertion [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
^
$
\b
\B
(?=
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?!
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?<=
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?<!
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
Quantifier ::
QuantifierPrefix
QuantifierPrefix
?
QuantifierPrefix ::
*
+
?
{
DecimalDigits [~Sep]
}
{
DecimalDigits [~Sep]
,}
{
DecimalDigits [~Sep]
,
DecimalDigits [~Sep]
}
Atom [UnicodeMode, UnicodeSetsMode,
NamedCaptureGroups] ::
PatternCharacter
.
\
AtomEscape [?UnicodeMode,
?NamedCaptureGroups]
CharacterClass [?UnicodeMode,
?UnicodeSetsMode]
(
GroupSpecifier [?UnicodeMode] opt
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
:
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
RegularExpressionModifiers
::
[empty]
RegularExpressionModifiers
RegularExpressionModifier
RegularExpressionModifier
:: one of i m
s
SyntaxCharacter ::
one of ^ $ \
. * + ? (
) [ ] { }
|
PatternCharacter ::
SourceCharacter but not
SyntaxCharacter
AtomEscape [UnicodeMode,
NamedCaptureGroups] ::
DecimalEscape
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode]
[+NamedCaptureGroups]
k
GroupName [?UnicodeMode]
CharacterEscape [UnicodeMode]
::
ControlEscape
c
AsciiLetter
0
[lookahead ∉ DecimalDigit ]
HexEscapeSequence
RegExpUnicodeEscapeSequence [?UnicodeMode]
IdentityEscape [?UnicodeMode]
ControlEscape ::
one of f n r
t v
GroupSpecifier [UnicodeMode]
::
?
GroupName [?UnicodeMode]
GroupName [UnicodeMode]
::
<
RegExpIdentifierName [?UnicodeMode]
>
RegExpIdentifierName [UnicodeMode]
::
RegExpIdentifierStart [?UnicodeMode]
RegExpIdentifierName [?UnicodeMode]
RegExpIdentifierPart [?UnicodeMode]
RegExpIdentifierStart [UnicodeMode]
::
IdentifierStartChar
\
RegExpUnicodeEscapeSequence [+UnicodeMode]
[~UnicodeMode]
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpIdentifierPart [UnicodeMode]
::
IdentifierPartChar
\
RegExpUnicodeEscapeSequence [+UnicodeMode]
[~UnicodeMode]
UnicodeLeadSurrogate
UnicodeTrailSurrogate
RegExpUnicodeEscapeSequence [UnicodeMode]
:: [+UnicodeMode]
u
HexLeadSurrogate
\u
HexTrailSurrogate
[+UnicodeMode]
u
HexLeadSurrogate
[+UnicodeMode]
u
HexTrailSurrogate
[+UnicodeMode]
u
HexNonSurrogate
[~UnicodeMode]
u
Hex4Digits
[+UnicodeMode]
u{
CodePoint
}
UnicodeLeadSurrogate ::
any Unicode code point in the inclusive interval from U+D800 to U+DBFF
UnicodeTrailSurrogate
::
any Unicode code point in the inclusive interval from U+DC00 to U+DFFF
Each \u HexTrailSurrogate for which the choice of
associated u HexLeadSurrogate is ambiguous shall be associated
with the nearest possible u HexLeadSurrogate that would otherwise have no
corresponding \u HexTrailSurrogate .
HexLeadSurrogate ::
Hex4Digits
but only if the MV of Hex4Digits is in
the inclusive
interval from 0xD800 to 0xDBFF
HexTrailSurrogate ::
Hex4Digits
but only if the MV of Hex4Digits is in
the inclusive
interval from 0xDC00 to 0xDFFF
HexNonSurrogate ::
Hex4Digits
but only if the MV of Hex4Digits is
not in the inclusive
interval from 0xD800 to 0xDFFF
IdentityEscape [UnicodeMode]
:: [+UnicodeMode]
SyntaxCharacter
[+UnicodeMode]
/
[~UnicodeMode]
SourceCharacter but not
UnicodeIDContinue
DecimalEscape ::
NonZeroDigit
DecimalDigits [~Sep] opt
[lookahead ∉ DecimalDigit ]
CharacterClassEscape [UnicodeMode]
::
d
D
s
S
w
W
[+UnicodeMode]
p{
UnicodePropertyValueExpression
}
[+UnicodeMode]
P{
UnicodePropertyValueExpression
}
UnicodePropertyValueExpression
::
UnicodePropertyName
=
UnicodePropertyValue
LoneUnicodePropertyNameOrValue
UnicodePropertyName ::
UnicodePropertyNameCharacters
UnicodePropertyNameCharacters
::
UnicodePropertyNameCharacter
UnicodePropertyNameCharacters opt
UnicodePropertyValue ::
UnicodePropertyValueCharacters
LoneUnicodePropertyNameOrValue
::
UnicodePropertyValueCharacters
UnicodePropertyValueCharacters
::
UnicodePropertyValueCharacter
UnicodePropertyValueCharacters opt
UnicodePropertyValueCharacter
::
UnicodePropertyNameCharacter
DecimalDigit
UnicodePropertyNameCharacter
::
AsciiLetter
_
CharacterClass [UnicodeMode,
UnicodeSetsMode] ::
[
[lookahead ≠ ^ ]
ClassContents [?UnicodeMode,
?UnicodeSetsMode]
]
[^
ClassContents [?UnicodeMode,
?UnicodeSetsMode]
]
ClassContents [UnicodeMode,
UnicodeSetsMode] ::
[empty]
[~UnicodeSetsMode]
NonemptyClassRanges [?UnicodeMode]
[+UnicodeSetsMode]
ClassSetExpression
NonemptyClassRanges [UnicodeMode]
::
ClassAtom [?UnicodeMode]
ClassAtom [?UnicodeMode]
NonemptyClassRangesNoDash [?UnicodeMode]
ClassAtom [?UnicodeMode]
-
ClassAtom [?UnicodeMode]
ClassContents [?UnicodeMode,
~UnicodeSetsMode]
NonemptyClassRangesNoDash [UnicodeMode]
::
ClassAtom [?UnicodeMode]
ClassAtomNoDash [?UnicodeMode]
NonemptyClassRangesNoDash [?UnicodeMode]
ClassAtomNoDash [?UnicodeMode]
-
ClassAtom [?UnicodeMode]
ClassContents [?UnicodeMode,
~UnicodeSetsMode]
ClassAtom [UnicodeMode]
::
-
ClassAtomNoDash [?UnicodeMode]
ClassAtomNoDash [UnicodeMode]
::
SourceCharacter but not one of
\ or ] or -
\
ClassEscape [?UnicodeMode]
ClassEscape [UnicodeMode]
::
b
[+UnicodeMode]
-
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode]
ClassSetExpression ::
ClassUnion
ClassIntersection
ClassSubtraction
ClassUnion ::
ClassSetRange
ClassUnion opt
ClassSetOperand
ClassUnion opt
ClassIntersection ::
ClassSetOperand
&&
[lookahead ≠ & ]
ClassSetOperand
ClassIntersection
&&
[lookahead ≠ & ]
ClassSetOperand
ClassSubtraction ::
ClassSetOperand
--
ClassSetOperand
ClassSubtraction
--
ClassSetOperand
ClassSetRange ::
ClassSetCharacter
-
ClassSetCharacter
ClassSetOperand ::
NestedClass
ClassStringDisjunction
ClassSetCharacter
NestedClass ::
[
[lookahead ≠ ^ ]
ClassContents [+UnicodeMode,
+UnicodeSetsMode]
]
[^
ClassContents [+UnicodeMode,
+UnicodeSetsMode]
]
\
CharacterClassEscape [+UnicodeMode]
ClassStringDisjunction
::
\q{
ClassStringDisjunctionContents
}
ClassStringDisjunctionContents
::
ClassString
ClassString
|
ClassStringDisjunctionContents
ClassString ::
[empty]
NonEmptyClassString
NonEmptyClassString ::
ClassSetCharacter
NonEmptyClassString opt
ClassSetCharacter ::
[lookahead ∉ ClassSetReservedDoublePunctuator ]
SourceCharacter but not
ClassSetSyntaxCharacter
\
CharacterEscape [+UnicodeMode]
\
ClassSetReservedPunctuator
\b
ClassSetReservedDoublePunctuator
:: one of &&
!! ## $$ %% **
++ ,, .. :: ;;
<< == >> ??
@@ ^^ `` ~~
ClassSetSyntaxCharacter
:: one of ( )
[ ] { } /
- \ |
ClassSetReservedPunctuator
:: one of & -
! # % , :
; < = > @
` ~
Annex B (normative) Additional ECMAScript
Features for Web Browsers
The ECMAScript language syntax and semantics defined in this annex are required when the ECMAScript
host is a web browser. The content
of this annex is normative but optional if the ECMAScript host is not a web browser.
Note
This annex describes various legacy features and other characteristics of web browser ECMAScript
hosts . All of the language
features and behaviours specified in this annex have one or more undesirable characteristics and
in the absence of legacy usage would be removed from this specification. However, the usage of
these features by large numbers of existing web pages means that web browsers must continue to
support them. The specifications in this annex define the requirements for interoperable
implementations of these legacy features.
These features are not considered part of the core ECMAScript language. Programmers should not
use or assume the existence of these features and behaviours when writing new ECMAScript code.
ECMAScript implementations are discouraged from implementing these features unless the
implementation is part of a web browser or is required to run the same legacy ECMAScript code
that web browsers encounter.
B.1 Additional Syntax
B.1.2 Regular Expressions Patterns
The syntax of 22.2.1 is modified and extended as follows. These
changes introduce ambiguities that are broken by the ordering of grammar productions and by
contextual information. When parsing using the following grammar, each alternative is considered
only if previous production alternatives do not match.
This alternative pattern grammar and semantics only changes the syntax and semantics of BMP
patterns. The following grammar extensions include productions parameterized with the
[UnicodeMode] parameter. However, none of these extensions change the syntax of Unicode patterns
recognized when parsing with the [UnicodeMode] parameter present on the goal
symbol .
Syntax
Term [UnicodeMode,
UnicodeSetsMode, NamedCaptureGroups]
:: [+UnicodeMode]
Assertion [+UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
[+UnicodeMode]
Atom [+UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
Quantifier
[+UnicodeMode]
Atom [+UnicodeMode, ?UnicodeSetsMode,
?NamedCaptureGroups]
[~UnicodeMode]
QuantifiableAssertion [?NamedCaptureGroups]
Quantifier
[~UnicodeMode]
Assertion [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
[~UnicodeMode]
ExtendedAtom [?NamedCaptureGroups]
Quantifier
[~UnicodeMode]
ExtendedAtom [?NamedCaptureGroups]
Assertion [UnicodeMode,
UnicodeSetsMode, NamedCaptureGroups]
::
^
$
\b
\B
[+UnicodeMode]
(?=
Disjunction [+UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
[+UnicodeMode]
(?!
Disjunction [+UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
[~UnicodeMode]
QuantifiableAssertion [?NamedCaptureGroups]
(?<=
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
(?<!
Disjunction [?UnicodeMode,
?UnicodeSetsMode, ?NamedCaptureGroups]
)
QuantifiableAssertion [NamedCaptureGroups]
::
(?=
Disjunction [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
)
(?!
Disjunction [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
)
ExtendedAtom [NamedCaptureGroups]
::
.
\
AtomEscape [~UnicodeMode,
?NamedCaptureGroups]
\
[lookahead = c ]
CharacterClass [~UnicodeMode,
~UnicodeSetsMode]
(
GroupSpecifier [~UnicodeMode] opt
Disjunction [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
:
Disjunction [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
)
(?
RegularExpressionModifiers
-
RegularExpressionModifiers
:
Disjunction [~UnicodeMode,
~UnicodeSetsMode, ?NamedCaptureGroups]
)
InvalidBracedQuantifier
ExtendedPatternCharacter
InvalidBracedQuantifier
::
{
DecimalDigits [~Sep]
}
{
DecimalDigits [~Sep]
,}
{
DecimalDigits [~Sep]
,
DecimalDigits [~Sep]
}
ExtendedPatternCharacter
::
SourceCharacter
but not one of ^
$
\
.
*
+
?
(
)
[
|
AtomEscape [UnicodeMode,
NamedCaptureGroups] ::
[+UnicodeMode]
DecimalEscape
[~UnicodeMode]
DecimalEscape
but only if the CapturingGroupNumber
of DecimalEscape
is ≤ CountLeftCapturingParensWithin (the
Pattern containing
DecimalEscape )
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode,
?NamedCaptureGroups]
[+NamedCaptureGroups]
k
GroupName [?UnicodeMode]
CharacterEscape [UnicodeMode,
NamedCaptureGroups] ::
ControlEscape
c
AsciiLetter
0
[lookahead ∉ DecimalDigit ]
HexEscapeSequence
RegExpUnicodeEscapeSequence [?UnicodeMode]
[~UnicodeMode]
LegacyOctalEscapeSequence
IdentityEscape [?UnicodeMode,
?NamedCaptureGroups]
IdentityEscape [UnicodeMode,
NamedCaptureGroups] ::
[+UnicodeMode]
SyntaxCharacter
[+UnicodeMode]
/
[~UnicodeMode]
SourceCharacterIdentityEscape [?NamedCaptureGroups]
SourceCharacterIdentityEscape [NamedCaptureGroups]
:: [~NamedCaptureGroups]
SourceCharacter
but not c
[+NamedCaptureGroups]
SourceCharacter
but not one of c or k
ClassAtomNoDash [UnicodeMode,
NamedCaptureGroups] ::
SourceCharacter
but not one of \ or ] or
-
\
ClassEscape [?UnicodeMode,
?NamedCaptureGroups]
\
[lookahead = c ]
ClassEscape [UnicodeMode,
NamedCaptureGroups] ::
b
[+UnicodeMode]
-
[~UnicodeMode]
c
ClassControlLetter
CharacterClassEscape [?UnicodeMode]
CharacterEscape [?UnicodeMode,
?NamedCaptureGroups]
ClassControlLetter
::
DecimalDigit
_
Note
When the same left-hand sides occurs with both [+UnicodeMode] and [~UnicodeMode] guards
it is to control the disambiguation priority.
B.1.2.1 Static Semantics: Early Errors
The semantics of 22.2.1.1 is
extended as follows:
ExtendedAtom
:: InvalidBracedQuantifier
It is a Syntax Error if any source text is matched by this production.
Additionally, the rules for the following productions are modified with the addition of the
highlighted text:
NonemptyClassRanges
::
ClassAtom
-
ClassAtom
ClassContents
NonemptyClassRangesNoDash
::
ClassAtomNoDash
-
ClassAtom
ClassContents
B.1.2.2 Static Semantics: CountLeftCapturingParensWithin and
CountLeftCapturingParensBefore
In the definitions of CountLeftCapturingParensWithin
and CountLeftCapturingParensBefore ,
references to “
Atom ::
(
GroupSpecifier opt
Disjunction
)
” are to be interpreted as meaning “
Atom ::
(
GroupSpecifier opt
Disjunction
)
” or “
ExtendedAtom
::
(
GroupSpecifier opt
Disjunction
)
”.
B.1.2.3 Static Semantics: IsCharacterClass
The semantics of 22.2.1.6 is
extended as follows:
ClassAtomNoDash
::
\
[lookahead = c ]
Return false .
B.1.2.4 Static Semantics: CharacterValue
The semantics of 22.2.1.7 is
extended as follows:
ClassAtomNoDash
::
\
[lookahead = c ]
Return the numeric value of U+005C (REVERSE SOLIDUS).
ClassEscape
::
c
ClassControlLetter
Let ch be the code point matched by ClassControlLetter .
Let i be the numeric value of ch .
Return the remainder of dividing i by 32.
CharacterEscape
:: LegacyOctalEscapeSequence
Return the MV of LegacyOctalEscapeSequence
(see 12.9.4.3 ).
B.1.2.5 Runtime Semantics: CompileSubpattern
The semantics of CompileSubpattern is extended as
follows:
The rule for
Term ::
QuantifiableAssertion
Quantifier
is the same as for
Term ::
Atom
Quantifier
but with QuantifiableAssertion
substituted for Atom .
The rule for
Term ::
ExtendedAtom
Quantifier
is the same as for
Term ::
Atom
Quantifier
but with ExtendedAtom substituted for Atom .
The rule for
Term :: ExtendedAtom
is the same as for
Term :: Atom
but with ExtendedAtom substituted for Atom .
B.1.2.6 Runtime Semantics: CompileAssertion
CompileAssertion rules for the
Assertion
::
(?=
Disjunction
)
and
Assertion
::
(?!
Disjunction
)
productions are also used for the QuantifiableAssertion
productions, but with QuantifiableAssertion
substituted for Assertion .
B.1.2.7 Runtime Semantics: CompileAtom
CompileAtom rules for the Atom productions except for
Atom :: PatternCharacter
are also used for the ExtendedAtom productions, but with
ExtendedAtom
substituted for Atom . The
following rules, with parameter direction , are also added:
ExtendedAtom
::
\
[lookahead = c ]
Let A be the CharSet containing the single
character \ U+005C (REVERSE SOLIDUS).
Return CharacterSetMatcher (rer ,
A , false , direction ).
ExtendedAtom
:: ExtendedPatternCharacter
Let ch be the character represented by ExtendedPatternCharacter .
Let A be a one-element CharSet containing the
character ch .
Return CharacterSetMatcher (rer ,
A , false , direction ).
B.1.2.8 Runtime Semantics: CompileToCharSet
The semantics of 22.2.2.9 is extended as follows:
The following two rules replace the corresponding rules of CompileToCharSet .
NonemptyClassRanges
::
ClassAtom
-
ClassAtom
ClassContents
Let A be CompileToCharSet of the first
ClassAtom with
argument rer .
Let B be CompileToCharSet of the second
ClassAtom with
argument rer .
Let C be CompileToCharSet of ClassContents with
argument rer .
Let D be CharacterRangeOrUnion (rer ,
A , B ).
Return the union of D and C .
NonemptyClassRangesNoDash
::
ClassAtomNoDash
-
ClassAtom
ClassContents
Let A be CompileToCharSet of ClassAtomNoDash with
argument rer .
Let B be CompileToCharSet of ClassAtom with argument
rer .
Let C be CompileToCharSet of ClassContents with
argument rer .
Let D be CharacterRangeOrUnion (rer ,
A , B ).
Return the union of D and C .
In addition, the following rules are added to CompileToCharSet .
ClassEscape
::
c
ClassControlLetter
Let cv be the CharacterValue
of this ClassEscape .
Let c be the character whose character value is cv .
Return the CharSet containing the single
character c .
ClassAtomNoDash
::
\
[lookahead = c ]
Return the CharSet containing the single
character \ U+005C (REVERSE SOLIDUS).
Note
This production can only be reached from the sequence
\c within a character class where it is not followed by an acceptable
control character.
B.1.2.8.1 CharacterRangeOrUnion ( rer ,
A , B )
The abstract operation CharacterRangeOrUnion takes arguments rer (a RegExp
Record ), A (a CharSet ), and B
(a CharSet ) and returns a CharSet . It performs the following steps
when called:
If HasEitherUnicodeFlag (rer )
is false , then
If A does not contain exactly one character or B
does not contain exactly one character, then
Let C be the CharSet
containing the single character - U+002D
(HYPHEN-MINUS).
Return the union of CharSets
A , B and C .
Return CharacterRange (A ,
B ).
B.1.2.9 Static Semantics: ParsePattern ( patternText ,
u , v )
The semantics of 22.2.3.4 is extended as follows:
The abstract operation ParsePattern takes arguments
patternText (a sequence of Unicode code points), u (a Boolean), and
v (a Boolean). It performs the following steps when called:
If v is true and u is
true , then
Let parseResult be a List
containing one or more SyntaxError objects.
Else if v is true , then
Let parseResult be ParseText (patternText ,
Pattern [+UnicodeMode,
+UnicodeSetsMode,
+NamedCaptureGroups] ).
Else if u is true , then
Let parseResult be ParseText (patternText ,
Pattern [+UnicodeMode,
~UnicodeSetsMode,
+NamedCaptureGroups] ).
Else,
Let parseResult be ParseText (patternText ,
Pattern [~UnicodeMode,
~UnicodeSetsMode,
~NamedCaptureGroups] ).
If parseResult is a Parse
Node and parseResult contains a GroupName , then
Set parseResult to ParseText (patternText ,
Pattern [~UnicodeMode,
~UnicodeSetsMode,
+NamedCaptureGroups] ).
Return parseResult .
B.2 Additional Built-in Properties
When the ECMAScript host is a
web browser the following additional properties of the standard built-in objects are defined.
B.2.1 Additional Properties of the Global Object
The entries in Table 102 are added
to Table 6 .
Table 102: Additional Well-known Intrinsic Objects
B.2.1.1 escape ( string )
This function is a property of the global object . It computes a new version of
a String value in which certain code units have been replaced by a hexadecimal escape
sequence.
When replacing a code unit of numeric value less than or equal to 0x00FF, a two-digit escape
sequence of the form %xx is used. When replacing a code unit of
numeric value strictly greater than 0x00FF, a four-digit escape sequence of the form
%uxxxx is used.
It is the %escape% intrinsic object.
It performs the following steps when called:
Set string to ? ToString (string ).
Let len be the length of string .
Let R be the empty String.
Let unescapedSet be the string-concatenation of
the ASCII word characters and
"@*+-./" .
Let k be 0.
Repeat, while k < len ,
Let C be the code unit at index k within
string .
If unescapedSet contains C , then
Let S be C .
Else,
Let n be the numeric value of C .
If n < 256, then
Let hex be the String representation of
n , formatted as an uppercase hexadecimal number.
Let S be the string-concatenation
of "%" and StringPad (hex ,
2, "0" , start ).
Else,
Let hex be the String representation of
n , formatted as an uppercase hexadecimal number.
Let S be the string-concatenation
of "%u" and StringPad (hex ,
4, "0" , start ).
Set R to the string-concatenation of
R and S .
Set k to k + 1.
Return R .
Note
The encoding is partly based on the encoding described in RFC 1738, but the entire
encoding specified in this standard is described above without regard to the
contents of RFC 1738. This encoding does not reflect changes to RFC 1738 made by RFC
3986.
B.2.1.2 unescape ( string )
This function is a property of the global object . It computes a new version of
a String value in which each escape sequence of the sort that might be introduced by the
escape function is replaced with the code unit that it represents.
It is the %unescape% intrinsic object.
It performs the following steps when called:
Set string to ? ToString (string ).
Let len be the length of string .
Let R be the empty String.
Let k be 0.
Repeat, while k < len ,
Let C be the code unit at index k within
string .
If C is the code unit 0x0025 (PERCENT SIGN), then
Let hexDigits be the empty String.
Let optionalAdvance be 0.
If k + 5 < len and the code unit at index
k + 1 within string is the code unit 0x0075
(LATIN SMALL LETTER U), then
Set hexDigits to the substring of
string from k + 2 to k + 6.
Set optionalAdvance to 5.
Else if k + 3 ≤ len , then
Set hexDigits to the substring of
string from k + 1 to k + 3.
Set optionalAdvance to 2.
Let parseResult be ParseText (hexDigits ,
HexDigits [~Sep] ).
If parseResult is a Parse Node ,
then
Let n be the MV of parseResult .
Set C to the code unit whose numeric value is
n .
Set k to k +
optionalAdvance .
Set R to the string-concatenation of
R and C .
Set k to k + 1.
Return R .
B.2.2 Additional Properties of the String.prototype Object
B.2.2.1 String.prototype.substr ( start ,
length )
This method returns a substring of the result of converting the
this value to a String, starting from index start and running
for length code units (or through the end of the String if length is
undefined ). If start is negative, it is treated as sourceLength + start where
sourceLength is the length of the String. The result is a String value,
not a String object.
It performs the following steps when called:
Let O be ? RequireObjectCoercible (this
value).
Let S be ? ToString (O ).
Let size be the length of S .
Let intStart be ? ToIntegerOrInfinity (start ).
If intStart = -∞, set intStart to 0.
Else if intStart < 0, set intStart to max (size +
intStart , 0).
Else, set intStart to min (intStart , size ).
If length is undefined , let intLength be
size ; otherwise let intLength be ? ToIntegerOrInfinity (length ).
Set intLength to the result of clamping intLength
between 0 and size .
Let intEnd be min (intStart +
intLength , size ).
Return the substring of S from
intStart to intEnd .
Note
This method is intentionally generic; it does not require that its
this value be a String object. Therefore it can be transferred to
other kinds of objects for use as a method.
B.2.2.2 String.prototype.anchor ( name )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"a" , "name" , name ).
B.2.2.2.1 CreateHTML ( string , tag ,
attribute , value )
The abstract operation CreateHTML takes arguments string (an ECMAScript language value ),
tag (a String), attribute (a String), and value (an
ECMAScript language value )
and returns either a normal
completion containing a String or a throw
completion . It performs the following steps when called:
Let str be ? RequireObjectCoercible (string ).
Let S be ? ToString (str ).
Let p1 be the string-concatenation of
"<" and tag .
If attribute is not the empty String, then
Let V be ? ToString (value ).
Let escapedV be the String value that is the same as
V except that each occurrence of the code unit 0x0022
(QUOTATION MARK) in V has been replaced with the six code
unit sequence """ .
Set p1 to the string-concatenation
of:
p1
the code unit 0x0020 (SPACE)
attribute
the code unit 0x003D (EQUALS SIGN)
the code unit 0x0022 (QUOTATION MARK)
escapedV
the code unit 0x0022 (QUOTATION MARK)
Let p2 be the string-concatenation of
p1 and ">" .
Let p3 be the string-concatenation of
p2 and S .
Let p4 be the string-concatenation of
p3 , "</" , tag , and
">" .
Return p4 .
B.2.2.3 String.prototype.big ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"big" , "" , "" ).
B.2.2.4 String.prototype.blink ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"blink" , "" , "" ).
B.2.2.5 String.prototype.bold ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"b" , "" , "" ).
B.2.2.6 String.prototype.fixed ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"tt" , "" , "" ).
B.2.2.7 String.prototype.fontcolor ( colour )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"font" , "color" , colour ).
B.2.2.8 String.prototype.fontsize ( size )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"font" , "size" , size ).
B.2.2.9 String.prototype.italics ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"i" , "" , "" ).
B.2.2.10 String.prototype.link ( url )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"a" , "href" , url ).
B.2.2.11 String.prototype.small ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"small" , "" , "" ).
B.2.2.12 String.prototype.strike ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"strike" , "" , "" ).
B.2.2.13 String.prototype.sub ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"sub" , "" , "" ).
B.2.2.14 String.prototype.sup ( )
This method performs the following steps when called:
Let S be the this value.
Return ? CreateHTML (S ,
"sup" , "" , "" ).
B.2.2.15 String.prototype.trimLeft ( )
Note
The property "trimStart" is preferred. The
"trimLeft" property is provided principally for compatibility
with old code. It is recommended that the "trimStart" property be
used in new ECMAScript code.
The initial value of the "trimLeft" property is
%String.prototype.trimStart%, defined in 22.1.3.34 .
B.2.2.16 String.prototype.trimRight ( )
Note
The property "trimEnd" is preferred. The
"trimRight" property is provided principally for compatibility
with old code. It is recommended that the "trimEnd" property be
used in new ECMAScript code.
The initial value of the "trimRight" property is
%String.prototype.trimEnd%, defined in 22.1.3.33 .
B.2.3 Additional Properties of the Date.prototype Object
B.2.3.1 Date.prototype.getYear ( )
Note
The getFullYear method is preferred for nearly all purposes, because it
avoids the “year 2000 problem.”
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
If t is NaN , return NaN .
Return YearFromTime (LocalTime (t )) -
1900 𝔽 .
B.2.3.2 Date.prototype.setYear ( year )
Note
The setFullYear method is preferred for nearly all purposes, because it
avoids the “year 2000 problem.”
This method performs the following steps when called:
Let dateObject be the this value.
Perform ? RequireInternalSlot (dateObject ,
[[DateValue]] ).
Let t be dateObject .[[DateValue]] .
Let y be ? ToNumber (year ).
If t is NaN , set t to
+0 𝔽 ; otherwise set t to LocalTime (t ).
Let yyyy be MakeFullYear (y ).
Let d be MakeDay (yyyy , MonthFromTime (t ),
DateFromTime (t )).
Let date be MakeDate (d , TimeWithinDay (t )).
Let u be TimeClip (UTC (date )).
Set dateObject .[[DateValue]] to u .
Return u .
B.2.3.3 Date.prototype.toGMTString ( )
Note
The toUTCString method is preferred. This method is provided principally
for compatibility with old code.
The initial value of the "toGMTString" property is
%Date.prototype.toUTCString%, defined in 21.4.4.43 .
B.2.4 Additional Properties of the RegExp.prototype Object
B.2.4.1 RegExp.prototype.compile ( pattern ,
flags )
This method performs the following steps when called:
Let O be the this value.
Perform ? RequireInternalSlot (O ,
[[RegExpMatcher]] ).
If pattern is an Object and pattern
has a [[RegExpMatcher]] internal slot, then
If flags is not undefined , throw a
TypeError exception.
Let P be pattern .[[OriginalSource]] .
Let F be pattern .[[OriginalFlags]] .
Else,
Let P be pattern .
Let F be flags .
Return ? RegExpInitialize (O ,
P , F ).
Note
This method completely reinitializes the this value RegExp with a
new pattern and flags. An implementation may interpret use of this method as an
assertion that the resulting RegExp object will be used multiple times and hence is
a candidate for extra optimization.
B.3 Other Additional Features
B.3.1 Labelled Function Declarations
Prior to ECMAScript 2015, the specification of LabelledStatement did not allow for the
association of a statement label with a FunctionDeclaration . However, a labelled
FunctionDeclaration was
an allowable extension for non-strict code and most browser-hosted
ECMAScript implementations supported that extension. In ECMAScript 2015 and later, the grammar
production for LabelledStatement permits use of FunctionDeclaration as a
LabelledItem but 14.13.1
includes an Early Error rule that produces a Syntax Error if that occurs. That rule is modified
with the addition of the highlighted text:
LabelledItem : FunctionDeclaration
It is a Syntax Error if any source text that is strict mode
code is matched by this production.
Note
B.3.2 Block-Level Function Declarations Web Legacy Compatibility
Semantics
Prior to ECMAScript 2015, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an
element of a Block statement's
StatementList . However,
support for that form of FunctionDeclaration was an allowable
extension and most browser-hosted ECMAScript implementations permitted them. Unfortunately, the
semantics of such declarations differ among those implementations. Because of these semantic
differences, existing web ECMAScript source text that uses Block level function declarations is only
portable among browser implementations if the usage only depends upon the semantic intersection
of all of the browser implementations for such declarations. The following are the use cases
that fall within that intersection semantics:
A function is declared and only referenced within a single block.
One or more FunctionDeclaration s whose
BindingIdentifier is the name
f occur within the function code of an enclosing function g
and that declaration is nested within a Block .
No other declaration of f that is not a var declaration
occurs within the function code of g .
All occurrences of f as an IdentifierReference are within
the StatementList
of the Block containing
the declaration of f .
A function is declared and possibly used within a single Block but also referenced by an inner function
definition that is not contained within that same Block .
One or more FunctionDeclaration s whose
BindingIdentifier is the name
f occur within the function code of an enclosing function g
and that declaration is nested within a Block .
No other declaration of f that is not a var declaration
occurs within the function code of g .
There may be occurrences of f as an IdentifierReference within the
StatementList of
the Block containing the
declaration of f .
There is at least one occurrence of f as an IdentifierReference within
another function h that is nested within g and no other
declaration of f shadows the references to f from within
h .
All invocations of h occur after the declaration of f has been
evaluated.
A function is declared and possibly used within a single block but also referenced within
subsequent blocks.
One or more FunctionDeclaration whose
BindingIdentifier is the name
f occur within the function code of an enclosing function g
and that declaration is nested within a Block .
No other declaration of f that is not a var declaration
occurs within the function code of g .
There may be occurrences of f as an IdentifierReference within the
StatementList of
the Block containing the
declaration of f .
There is at least one occurrence of f as an IdentifierReference within the
function code of g that lexically follows the Block containing the declaration of
f .
The first use case is interoperable with the semantics of Block level function declarations provided by ECMAScript
2015. Any pre-existing ECMAScript source text that employs that use case
will operate using the Block level function declarations semantics defined by clauses 10 , 14 , and
15 .
ECMAScript 2015 interoperability for the second and third use cases requires the following
extensions to the clause 10 ,
clause 15 , clause
19.2.1 and
clause 16.1.7 semantics.
If an ECMAScript implementation has a mechanism for reporting diagnostic warning messages, a
warning should be produced when code contains a FunctionDeclaration for which these
compatibility semantics are applied and introduce observable differences from non-compatibility
semantics. For example, if a var binding is not introduced because its introduction would create
an early
error , a warning message should not be produced.
B.3.2.1 Changes to FunctionDeclarationInstantiation
During FunctionDeclarationInstantiation
the following steps are performed in place of step 31 :
If strict is false , then
For each FunctionDeclaration
f that is directly contained in the StatementList of any Block , CaseClause , or
DefaultClause x
such that code Contains
x is true , do
Let F be the StringValue
of the BindingIdentifier
of f .
If replacing the FunctionDeclaration
f with a VariableStatement
that has F as a BindingIdentifier
would not produce any Early Errors for func and
parameterNames does not contain F , then
NOTE: A var binding for F is only instantiated
here if it is neither a VarDeclaredName, the name of a
formal parameter, or another FunctionDeclaration .
If instantiatedVarNames does not contain
F and F is not
"arguments" , then
Perform
! varEnv .CreateMutableBinding(F ,
false ).
Perform
! varEnv .InitializeBinding(F ,
undefined ).
Append F to
instantiatedVarNames .
When the FunctionDeclaration
f is evaluated, perform the following steps in
place of the FunctionDeclaration
Evaluation
algorithm provided in 15.2.6 :
Let fEnv be the running
execution context 's
VariableEnvironment.
Let bEnv be the running
execution context 's
LexicalEnvironment.
Let fObj be
! bEnv .GetBindingValue(F ,
false ).
Perform
! fEnv .SetMutableBinding(F ,
fObj , false ).
Return unused .
B.3.2.2 Changes to GlobalDeclarationInstantiation
During GlobalDeclarationInstantiation
the following steps are performed in place of step 12 :
Perform the following steps:
Let strict be ScriptIsStrict of
script .
If strict is false , then
Let declaredFunctionOrVarNames be the list-concatenation
of declaredFunctionNames and declaredVarNames .
For each FunctionDeclaration
f that is directly contained in the StatementList of any
Block ,
CaseClause , or DefaultClause
x such that script Contains
x is true , do
Let F be the StringValue
of the BindingIdentifier
of f .
If replacing the FunctionDeclaration
f with a VariableStatement
that has F as a BindingIdentifier
would not produce any Early Errors for script ,
then
If HasLexicalDeclaration (env ,
F ) is false , then
Let fnDefinable be
? CanDeclareGlobalVar (env ,
F ).
If fnDefinable is
true , then
NOTE: A var binding for F
is only instantiated here if it is
neither a VarDeclaredName nor the
name of another FunctionDeclaration .
If
declaredFunctionOrVarNames
does not contain F , then
Perform ? CreateGlobalVarBinding (env ,
F ,
false ).
Append F to
declaredFunctionOrVarNames .
When the FunctionDeclaration
f is evaluated, perform
the following steps in place of the
FunctionDeclaration
Evaluation
algorithm provided in 15.2.6 :
Let gEnv be the
running
execution
context 's
VariableEnvironment.
Let bEnv be the
running
execution
context 's
LexicalEnvironment.
Let fObj be
! bEnv .GetBindingValue(F ,
false ).
Perform ? gEnv .SetMutableBinding (F ,
fObj ,
false ).
Return
unused .
B.3.2.3 Changes to EvalDeclarationInstantiation
During EvalDeclarationInstantiation
the following steps are performed in place of step 13 :
If strict is false , then
Let declaredFunctionOrVarNames be the list-concatenation of
declaredFunctionNames and declaredVarNames .
For each FunctionDeclaration
f that is directly contained in the StatementList of any Block , CaseClause , or
DefaultClause x
such that body Contains
x is true , do
Let F be the StringValue
of the BindingIdentifier
of f .
If replacing the FunctionDeclaration
f with a VariableStatement
that has F as a BindingIdentifier
would not produce any Early Errors for body , then
Let bindingExists be false .
Let thisEnv be lexEnv .
Assert : The following
loop will terminate.
Repeat, while thisEnv is not varEnv ,
If thisEnv is not an
Object Environment
Record , then
If
! thisEnv .HasBinding(F )
is true , then
Let bindingExists be
true .
Set thisEnv to thisEnv .[[OuterEnv]] .
If bindingExists is false and
varEnv is a Global
Environment Record , then
If HasLexicalDeclaration (varEnv ,
F ) is false , then
Let fnDefinable be
? CanDeclareGlobalVar (varEnv ,
F ).
Else,
Let fnDefinable be
false .
Else,
Let fnDefinable be
true .
If bindingExists is false and
fnDefinable is true , then
If declaredFunctionOrVarNames does not
contain F , then
If varEnv is a Global
Environment Record ,
then
Perform ? CreateGlobalVarBinding (varEnv ,
F ,
true ).
Else,
Let bindingExists be
! varEnv .HasBinding(F ).
If bindingExists is
false , then
Perform
! varEnv .CreateMutableBinding(F ,
true ).
Perform
! varEnv .InitializeBinding(F ,
undefined ).
Append F to
declaredFunctionOrVarNames .
When the FunctionDeclaration
f is evaluated, perform the following
steps in place of the FunctionDeclaration
Evaluation
algorithm provided in 15.2.6 :
Let gEnv be the running
execution context 's
VariableEnvironment.
Let bEnv be the running
execution context 's
LexicalEnvironment.
Let fObj be
! bEnv .GetBindingValue(F ,
false ).
Perform ? gEnv .SetMutableBinding (F ,
fObj , false ).
Return unused .
B.3.2.4 Changes to Block Static Semantics: Early Errors
The rules for the following production in 14.2.1 are modified
with the addition of the highlighted text:
Block :
{
StatementList
}
B.3.2.5 Changes to switch Statement Static
Semantics: Early Errors
The rules for the following production in 14.12.1
are modified with the addition of the highlighted text:
SwitchStatement
:
switch
(
Expression
)
CaseBlock
B.3.2.6 Changes to BlockDeclarationInstantiation
During BlockDeclarationInstantiation
the following steps are performed in place of step 3.a.ii.1 :
If ! env .HasBinding(dn ) is false , then
Perform ! env .CreateMutableBinding(dn ,
false ).
During BlockDeclarationInstantiation
the following steps are performed in place of step 3.b.iii :
Perform the following steps:
If the binding for fn in env is an uninitialized
binding, then
Perform ! env .InitializeBinding(fn ,
fo ).
Else,
Assert : d is a
FunctionDeclaration .
Perform ! env .SetMutableBinding(fn ,
fo , false ).
B.3.3 FunctionDeclarations in IfStatement Statement Clauses
The following augments the IfStatement production in 14.6 :
IfStatement [Yield, Await,
Return] :
if
(
Expression [+In, ?Yield,
?Await]
)
FunctionDeclaration [?Yield,
?Await, ~Default]
else
Statement [?Yield, ?Await,
?Return]
if
(
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
else
FunctionDeclaration [?Yield,
?Await, ~Default]
if
(
Expression [+In, ?Yield,
?Await]
)
FunctionDeclaration [?Yield,
?Await, ~Default]
else
FunctionDeclaration [?Yield,
?Await, ~Default]
if
(
Expression [+In, ?Yield,
?Await]
)
FunctionDeclaration [?Yield,
?Await, ~Default]
[lookahead ≠ else ]
This production only applies when parsing non-strict code . Source text matched
by this production is processed as if each matching occurrence of FunctionDeclaration [?Yield,
?Await, ~Default] was the sole StatementListItem of a
BlockStatement occupying
that position in the source text. The semantics of such a synthetic BlockStatement includes the web legacy
compatibility semantics specified in B.3.2 .
B.3.4 VariableStatements in Catch Blocks
The content of subclause 14.15.1 is
replaced with the following:
Catch :
catch
(
CatchParameter
)
Block
Note
The Block of a Catch clause may contain
var declarations that bind a name that is also bound by the CatchParameter . At
runtime, such bindings are instantiated in the VariableDeclarationEnvironment. They do
not shadow the same-named bindings introduced by the CatchParameter and hence the Initializer for such
var declarations will assign to the corresponding catch parameter rather
than the var binding.
This modified behaviour also applies to var and function declarations
introduced by direct
eval calls contained within the Block of a Catch clause. This change is accomplished by modifying
the algorithm of 19.2.1.3 as follows:
Step 3.d.i.2.a.i
is replaced by:
If thisEnv is not the Environment Record
for a Catch clause, throw a
SyntaxError exception.
Step 13.b.ii.4.a.i.i
is replaced by:
If thisEnv is not the Environment Record
for a Catch clause, let
bindingExists be true .
B.3.5 Initializers in ForIn Statement Heads
The following augments the ForInOfStatement production in
14.7.5 :
ForInOfStatement [Yield,
Await, Return] :
for
(
var
BindingIdentifier [?Yield,
?Await]
Initializer [~In, ?Yield,
?Await]
in
Expression [+In, ?Yield,
?Await]
)
Statement [?Yield, ?Await,
?Return]
This production only applies when parsing non-strict code .
The static semantics of ContainsDuplicateLabels
in 8.3.1 are augmented
with the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Return ContainsDuplicateLabels
of Statement with
argument labelSet .
The static semantics of ContainsUndefinedBreakTarget
in 8.3.2 are
augmented with the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Return ContainsUndefinedBreakTarget
of Statement with
argument labelSet .
The static semantics of ContainsUndefinedContinueTarget
in 8.3.3 are
augmented with the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Return ContainsUndefinedContinueTarget
of Statement with
arguments iterationSet and « ».
The static semantics of IsDestructuring in 14.7.5.2 are augmented with
the following:
BindingIdentifier
:
Identifier
yield
await
Return false .
The static semantics of VarDeclaredNames in
8.2.6 are augmented with
the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Let names1 be the BoundNames of BindingIdentifier .
Let names2 be the VarDeclaredNames of
Statement .
Return the list-concatenation of
names1 and names2 .
The static semantics of VarScopedDeclarations
in 8.2.7 are augmented
with the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Let declarations1 be « BindingIdentifier ».
Let declarations2 be the VarScopedDeclarations
of Statement .
Return the list-concatenation of
declarations1 and declarations2 .
The runtime semantics of ForInOfLoopEvaluation
in 14.7.5.5 are
augmented with the following:
ForInOfStatement
:
for
(
var
BindingIdentifier
Initializer
in
Expression
)
Statement
Let bindingId be the StringValue of BindingIdentifier .
Let lhs be ? ResolveBinding (bindingId ).
If IsAnonymousFunctionDefinition (Initializer ) is
true , then
Let value be ? NamedEvaluation of Initializer with
argument bindingId .
Else,
Let rhs be ? Evaluation of
Initializer .
Let value be ? GetValue (rhs ).
Perform ? PutValue (lhs , value ).
Let keyResult be ? ForIn/OfHeadEvaluation (« », Expression ,
enumerate ).
Return ? ForIn/OfBodyEvaluation (BindingIdentifier ,
Statement ,
keyResult , enumerate ,
var-binding , labelSet ).
B.3.6 The [[IsHTMLDDA]] Internal Slot
An [[IsHTMLDDA]] internal slot may exist on
host-defined objects. Objects with an [[IsHTMLDDA]] internal slot behave like undefined in
the ToBoolean and IsLooselyEqual abstract operations
and when used as an operand for the typeof operator .
Note
Objects with an [[IsHTMLDDA]] internal slot are never created by
this specification. However, the document.all
object in web browsers is a host-defined exotic object with this slot
that exists for web compatibility purposes. There are no other known examples of this
type of object and implementations should not create any with the exception of
document.all.
B.3.6.1 Changes to ToBoolean
The following step replaces step 3 of
ToBoolean :
If argument is an Object and argument
has an [[IsHTMLDDA]] internal slot, return
false .
B.3.6.2 Changes to IsLooselyEqual
The following steps replace step 4
of IsLooselyEqual :
Perform the following steps:
If x is an Object , x
has an [[IsHTMLDDA]] internal slot, and
y is either undefined or
null , return true .
If x is either undefined or
null , y is an Object ,
and y has an [[IsHTMLDDA]] internal
slot, return true .
B.3.6.3 Changes to the typeof Operator
The following step replaces step 12 of
the evaluation semantics
for typeof :
If val has an [[IsHTMLDDA]] internal slot,
return "undefined" .
B.3.7 Non-default behaviour in HostMakeJobCallback
The HostMakeJobCallback abstract operation
allows hosts which are web
browsers to specify non-default behaviour.
B.3.8 Non-default behaviour in HostEnsureCanAddPrivateElement
The HostEnsureCanAddPrivateElement
abstract operation allows hosts which are web browsers to specify non-default
behaviour.
B.3.9 Runtime Errors for Function Call Assignment Targets
When a function call (13.3.6 ) is used as an assignment target in
non-strict
code , instead of producing an early error , a
ReferenceError exception is thrown during evaluation of the assignment.
Note
When the assignment target is the LeftHandSideExpression of an
AssignmentExpression , the
assignment operator must be = or an AssignmentOperator ; in particular,
the allowance here does not apply to the logical assignment operators (??=,
&&=, ||=).
See step 1 of AssignmentTargetType
for
CallExpression :
CoverCallExpressionAndAsyncArrowHead
and
CallExpression :
CallExpression
Arguments
.
Annex C (informative) The Strict Mode of
ECMAScript
The strict mode restriction and exceptions
implements, interface, let, package,
private, protected, public, static, and
yield are reserved words within strict mode
code . (12.7.2 ).
A conforming implementation, when processing strict mode code , must disallow
instances of the productions
NumericLiteral ::
LegacyOctalIntegerLiteral
and
DecimalIntegerLiteral
:: NonOctalDecimalIntegerLiteral
.
A conforming implementation, when processing strict mode code , must disallow
instances of the productions
EscapeSequence ::
LegacyOctalEscapeSequence
and
EscapeSequence ::
NonOctalDecimalEscapeSequence
.
Assignment to an undeclared identifier or otherwise unresolvable reference does not create a
property in the global object . When a simple assignment occurs
within strict
mode code , its LeftHandSideExpression must not evaluate to
an unresolvable Reference. If it does a ReferenceError exception is thrown
(6.2.5.6 ). The
LeftHandSideExpression
also may not be a reference to a data property with the attribute value { [[Writable]] : false }, to an accessor
property with the attribute value { [[Set]] :
undefined }, nor to a non-existent property of an object whose [[Extensible]] internal slot is false . In these cases a
TypeError exception is thrown (13.15 ).
An IdentifierReference with
the StringValue
"eval" or "arguments" may not appear as the LeftHandSideExpression of an
Assignment operator (13.15 ) or of an UpdateExpression (13.4 ) or as the UnaryExpression operated upon by a Prefix
Increment (13.4.4 ) or a Prefix Decrement
(13.4.5 ) operator.
Arguments objects for strict functions define a non-configurable accessor
property "callee" which throws a
TypeError exception on access (10.4.4.6 ).
Arguments objects for strict functions do not dynamically share their
array-indexed
property values with the corresponding formal parameter bindings of their functions. (10.4.4 ).
For strict
functions , if an arguments object is created the binding of the local
identifier arguments to the arguments object is immutable and hence may not be the
target of an assignment expression. (10.2.11 ).
It is a SyntaxError if the StringValue of a BindingIdentifier is either
"eval" or "arguments" within strict mode
code (13.1.1 ).
Strict mode eval code cannot instantiate variables or functions in the variable environment of the
caller to eval. Instead, a new variable environment is created and that environment is used for
declaration binding instantiation for the eval code (19.2.1 ).
If this is evaluated within strict mode code , then the
this value is not coerced to an object. A this value of either
undefined or null is not converted to the global
object and primitive values are not converted to wrapper objects. The
this value passed via a function call (including calls made using
Function.prototype.apply and Function.prototype.call) do not coerce the
passed this value to an object (10.2.1.2 , 20.2.3.1 , 20.2.3.3 ).
When a delete operator occurs within strict mode code , a
SyntaxError is thrown if its UnaryExpression is a direct reference to a
variable, function argument, or function name (13.5.1.1 ).
When a delete operator occurs within strict mode code , a
TypeError is thrown if the property to be deleted has the attribute { [[Configurable]] : false } or otherwise cannot be deleted
(13.5.1.2 ).
Strict mode
code may not include a WithStatement . The occurrence of a WithStatement in such a context is a
SyntaxError (14.11.1 ).
It is a SyntaxError if a CatchParameter occurs within strict mode
code and the BoundNames of CatchParameter contains either
eval or arguments (14.15.1 ).
It is a SyntaxError if the same BindingIdentifier appears more than once in the
FormalParameters of a
strict
function . An attempt to create such a function using a Function, Generator,
or AsyncFunction constructor is a SyntaxError
(15.2.1 ,
20.2.1.1.1 ).
An implementation may not extend, beyond that defined in this specification, the meanings within
strict
functions of properties named "caller" or
"arguments" of function instances.
Annex D (informative) Host Layering Points
See 4.2 for the definition of host .
D.1 Host Hooks
HostCallJobCallback (...)
HostEnqueueFinalizationRegistryCleanupJob (...)
HostEnqueueGenericJob (...)
HostEnqueuePromiseJob (...)
HostEnqueueTimeoutJob (...)
HostEnsureCanCompileStrings (...)
HostFinalizeImportMeta (...)
HostGetImportMetaProperties (...)
HostGrowSharedArrayBuffer (...)
HostHasSourceTextAvailable (...)
HostLoadImportedModule (...)
HostGetSupportedImportAttributes (...)
HostMakeJobCallback (...)
HostPromiseRejectionTracker (...)
HostResizeArrayBuffer (...)
InitializeHostDefinedRealm (...)
D.2 Host-defined Fields
[[HostDefined]] on Realm Records : See Table
24 .
[[HostDefined]] on Script Records : See Table
39 .
[[HostDefined]] on Module Records : See
Table 43 .
[[HostDefined]] on JobCallback Records : See
Table
28 .
[[HostSynchronizesWith]] on Candidate Executions: See Table 101 .
[[IsHTMLDDA]] : See B.3.6 .
D.3 Host-defined Objects
The global
object : See clause 19 .
D.4 Running Jobs
Preparation steps before, and cleanup steps after, invocation of Job Abstract Closures . See 9.5 .
D.5 Internal Methods of Exotic Objects
Any of the essential internal methods in Table 4 for any
exotic
object not specified within this specification.
D.6 Built-in Objects and Methods
Any built-in objects and methods not defined within this specification, except as restricted in
17.1 .
Annex E (informative) Corrections and
Clarifications in ECMAScript 2015 with Possible Compatibility Impact
9.1.1.4.14 -9.1.1.4.17 Edition 5 and 5.1 used a
property existence test to determine whether a global object property corresponding to a new global
declaration already existed. ECMAScript 2015 uses an own property existence test. This corresponds to
what has been most commonly implemented by web browsers.
10.4.2.1 : The
5th Edition moved the capture of the current array length prior to the integer conversion of the
array index or new
length value. However, the captured length value could become invalid if the conversion process has the
side-effect of changing the array length. ECMAScript 2015 specifies that the current array length must
be captured after the possible occurrence of such side-effects.
21.4.1.31 : Previous
editions permitted the TimeClip abstract operation to return either
+0 𝔽 or -0 𝔽 as the representation of a 0
time value . ECMAScript 2015 specifies that
+0 𝔽 always returned. This means that for ECMAScript 2015 the time value of a Date is never observably
-0 𝔽 and methods that return time values never return
-0 𝔽 .
21.4.1.32 : If a UTC offset representation is
not present, the local time zone is used. Edition 5.1 incorrectly stated that a missing time zone should
be interpreted as "z" .
21.4.4.36 : If the year cannot be
represented using the Date Time String Format specified in 21.4.1.32 a RangeError exception
is thrown. Previous editions did not specify the behaviour for that case.
21.4.4.41 : Previous editions did not specify
the value returned by Date.prototype.toString when the time value is NaN .
ECMAScript 2015 specifies the result to be the String value "Invalid Date" .
22.2.4.1 , 22.2.6.13.1 : Any LineTerminator code points in
the value of the "source" property of a RegExp instance must be expressed using an
escape sequence. Edition 5.1 only required the escaping of /.
22.2.6.8 , 22.2.6.11 : In previous editions,
the specifications for String.prototype.match and String.prototype.replace was
incorrect for cases where the pattern argument was a RegExp value whose global flag is set.
The previous specifications stated that for each attempt to match the pattern, if lastIndex
did not change, it should be incremented by 1. The correct behaviour is that lastIndex
should be incremented by 1 only if the pattern matched the empty String.
23.1.3.30 : Previous editions did not specify how
a NaN value returned by a comparator was interpreted by
Array.prototype.sort. ECMAScript 2015 specifies that such as value is treated as if
+0 𝔽 was returned from the comparator . ECMAScript 2015 also
specifies that ToNumber
is applied to the result returned by a comparator . In previous editions, the effect of a
comparator result that is not a Number
value was implementation-defined . In practice,
implementations call ToNumber .
Annex F (informative) Additions and Changes
That Introduce Incompatibilities with Prior Editions
6.2.5 : In ECMAScript 2015,
Function calls are not allowed to return a Reference Record .
7.1.4.1 : In ECMAScript 2015,
ToNumber applied to a
String value now recognizes and converts BinaryIntegerLiteral and OctalIntegerLiteral numeric
strings. In previous editions such strings were converted to NaN .
9.3 : In
ECMAScript 2018, Template objects are canonicalized based on Parse Node (source location),
instead of across all occurrences of that template literal or tagged template in a Realm in previous editions.
12.2 : In
ECMAScript 2016, Unicode 8.0.0 or higher is mandated, as opposed to ECMAScript 2015 which mandated
Unicode 5.1. In particular, this caused U+180E MONGOLIAN VOWEL SEPARATOR, which was in the
Space_Separator (Zs) category and thus treated as whitespace in ECMAScript
2015, to be moved to the Format (Cf) category (as of Unicode 6.3.0). This
causes whitespace-sensitive methods to behave differently. For example,
"\u180E".trim().length was 0 in previous editions, but 1 in
ECMAScript 2016 and later. Additionally, ECMAScript 2017 mandated always using the latest version of the
Unicode Standard.
12.7 : In ECMAScript 2015, the valid code points
for an IdentifierName are specified
in terms of the Unicode properties “ID_Start” and “ID_Continue”. In previous editions, the valid IdentifierName or Identifier code points were specified by
enumerating various Unicode code point categories.
12.10.1 : In ECMAScript 2015,
Automatic Semicolon Insertion adds a semicolon at the end of a do-while statement if the semicolon is
missing. This change aligns the specification with the actual behaviour of most existing
implementations.
13.2.5.1 : In
ECMAScript 2015, it is no longer an early error to have duplicate property names in Object
Initializers.
13.15.1 : In
ECMAScript 2015, strict mode code containing an assignment to an
immutable binding such as the function name of a FunctionExpression does not produce an early error . Instead it
produces a runtime error.
14.2 : In ECMAScript 2015, a
StatementList beginning with the
token let followed by the input elements LineTerminator then Identifier is the start of a LexicalDeclaration . In previous editions, automatic
semicolon insertion would always insert a semicolon before the Identifier input element.
14.5 : In ECMAScript 2015, a StatementListItem beginning with the
token let followed by the token [ is the start of a LexicalDeclaration . In previous editions such a
sequence would be the start of an ExpressionStatement .
14.6.2 : In ECMAScript 2015,
the normal result of an IfStatement is
never the value empty . If no Statement part is evaluated or if the evaluated Statement part produces a normal completion containing
empty , the result of the IfStatement is undefined .
14.7 : In ECMAScript 2015, if the (
token of a for statement is immediately followed by the token sequence let [ then the
let is treated as the start of a LexicalDeclaration . In previous editions such a
token sequence would be the start of an Expression .
14.7 : In ECMAScript 2015, if the ( token of a
for-in statement is immediately followed by the token sequence let [ then the
let is treated as the start of a ForDeclaration . In previous editions such a token
sequence would be the start of an LeftHandSideExpression .
14.7 : Prior to ECMAScript 2015, an
initialization expression could appear as part of the VariableDeclaration that precedes the
in keyword . In ECMAScript 2015, the ForBinding in that same position does not
allow the occurrence of such an initializer. In ECMAScript 2017, such an initializer is permitted only
in non-strict
code .
14.7 : In ECMAScript 2015, the result of
evaluating an IterationStatement
is never a normal completion whose [[Value]] is empty . If the Statement part of an IterationStatement is not evaluated or if the final
evaluation of the Statement part produces
a normal completion whose [[Value]] is empty , the result of evaluating the IterationStatement is a normal completion whose [[Value]] is undefined .
14.11.2 : In ECMAScript
2015, the result of evaluating a WithStatement is never a normal completion whose [[Value]] is empty . If evaluation of the Statement part of a WithStatement produces a normal completion whose [[Value]] is empty , the result of evaluating the WithStatement is a normal completion whose [[Value]] is undefined .
14.12.4 : In ECMAScript
2015, the result of evaluating a SwitchStatement is never a normal completion whose [[Value]] is empty . If evaluation of the CaseBlock part of a SwitchStatement produces a normal completion whose [[Value]] is empty , the result of evaluating the SwitchStatement is a normal completion whose [[Value]] is undefined .
14.15 : In
ECMAScript 2015, it is an early
error for a Catch
clause to contain a var declaration for the same Identifier that appears as the Catch clause parameter. In previous editions, such a variable
declaration would be instantiated in the enclosing variable environment but the declaration's Initializer value would be assigned to the
Catch parameter.
14.15 ,
19.2.1.3 : In ECMAScript 2015, a runtime
SyntaxError is thrown if a Catch clause evaluates a non-strict direct eval
whose eval code includes a var or FunctionDeclaration declaration that binds
the same Identifier that appears as the
Catch clause parameter.
14.15.3 : In ECMAScript
2015, the result of a TryStatement is
never the value empty . If the Block part of a TryStatement evaluates to a normal completion containing
empty , the result of the TryStatement is undefined . If the
Block part of a TryStatement evaluates to a throw completion and it has a
Catch part that evaluates to a normal completion containing
empty , the result of the TryStatement is undefined if there is
no Finally clause or if its Finally clause evaluates to an
empty normal
completion .
15.4.5 In ECMAScript
2015, the function
objects that are created as the values of the [[Get]] or
[[Set]] attribute of accessor properties in an ObjectLiteral are not constructor functions and they do not have a
"prototype" own property. In the previous edition, they were constructors and had a
"prototype" property.
20.1.2.6 :
In ECMAScript 2015, if the argument to Object.freeze is not an object it is treated as if
it was a non-extensible ordinary object with no own properties. In the previous
edition, a non-object argument always causes a TypeError to be thrown.
20.1.2.8 : In ECMAScript 2015, if the
argument to Object.getOwnPropertyDescriptor is not an object an attempt is made to coerce
the argument using ToObject . If the coercion is successful the result is used
in place of the original argument value. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.10 : In ECMAScript 2015, if the
argument to Object.getOwnPropertyNames is not an object an attempt is made to coerce the
argument using ToObject . If the coercion is successful the result is used
in place of the original argument value. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.12 : In ECMAScript 2015, if the argument
to Object.getPrototypeOf is not an object an attempt is made to coerce the argument using
ToObject . If the
coercion is successful the result is used in place of the original argument value. In the previous
edition, a non-object argument always causes a TypeError to be thrown.
20.1.2.16 : In ECMAScript 2015, if the argument to
Object.isExtensible is not an object it is treated as if it was a non-extensible ordinary object
with no own properties. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.17 : In ECMAScript 2015, if the argument to
Object.isFrozen is not an object it is treated as if it was a non-extensible ordinary object
with no own properties. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.18 : In ECMAScript 2015, if the argument to
Object.isSealed is not an object it is treated as if it was a non-extensible ordinary object
with no own properties. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.19 : In
ECMAScript 2015, if the argument to Object.keys is not an object an attempt is made to
coerce the argument using ToObject . If the coercion is successful the result is used
in place of the original argument value. In the previous edition, a non-object argument always causes a
TypeError to be thrown.
20.1.2.20 : In ECMAScript 2015, if the
argument to Object.preventExtensions is not an object it is treated as if it was a
non-extensible ordinary
object with no own properties. In the previous edition, a non-object argument
always causes a TypeError to be thrown.
20.1.2.22 : In
ECMAScript 2015, if the argument to Object.seal is not an object it is treated as if it was
a non-extensible ordinary
object with no own properties. In the previous edition, a non-object argument
always causes a TypeError to be thrown.
20.2.3.2 : In ECMAScript 2015, the [[Prototype]] internal slot of a bound function is set to the [[GetPrototypeOf]] value of its target function. In the previous edition, [[Prototype]] was always set to %Function.prototype% .
20.2.4.1 : In ECMAScript 2015, the
"length" property of function instances is configurable. In previous editions it was
non-configurable.
20.5.6.2 : In ECMAScript
2015, the [[Prototype]] internal slot of a NativeError constructor is the Error
constructor . In
previous editions it was the Function prototype
object .
21.4.4 In ECMAScript 2015,
the Date prototype object is not
a Date instance. In previous editions it was a Date instance whose TimeValue was NaN .
22.1.3.12 In ECMAScript 2015, the
String.prototype.localeCompare function must treat Strings that are canonically equivalent
according to the Unicode Standard as being identical. In previous editions implementations were
permitted to ignore canonical equivalence and could instead use a bit-wise comparison.
22.1.3.28 and 22.1.3.30 In ECMAScript 2015,
lowercase/upper conversion processing operates on code points. In previous editions such the conversion
processing was only applied to individual code units. The only affected code points are those in the
Deseret block of Unicode.
22.1.3.32 In ECMAScript 2015, the
String.prototype.trim method is defined to recognize white space code points that may exist
outside of the Unicode BMP. However, as of Unicode 7 no such code points are defined. In previous
editions such code points would not have been recognized as white space.
22.2.4.1 In ECMAScript 2015, If the
pattern argument is a RegExp instance and the flags argument is not
undefined , a new RegExp instance is created just like pattern except that
pattern 's flags are replaced by the argument flags . In previous editions a
TypeError exception was thrown when pattern was a RegExp instance and
flags was not undefined .
22.2.6 In ECMAScript 2015,
the RegExp prototype object is
not a RegExp instance. In previous editions it was a RegExp instance whose pattern is the empty String.
22.2.6 In ECMAScript 2015,
"source" , "global" , "ignoreCase" , and
"multiline" are accessor properties defined on the RegExp prototype object . In
previous editions they were data properties defined on RegExp instances.
25.4.15 :
In ECMAScript 2019, Atomics.wake has been renamed to Atomics.notify to prevent
confusion with Atomics.wait.
27.1.6.4 , 27.6.3.6 : In ECMAScript 2019, the number of
Jobs enqueued by await
was reduced, which could create an observable difference in resolution order between a
then() call and an await expression.
Bibliography
IEEE 754-2019 : IEEE Standard for Floating-Point Arithmetic .
Institute of Electrical and Electronic Engineers, New York (2019)
Note
There are no normative changes between IEEE 754-2008 and IEEE 754-2019 that affect the
ECMA-262 specification.
The Unicode Standard , available at <https://unicode.org/versions/latest >
Unicode Technical Note #5: Canonical Equivalence in Applications , available at <https://unicode.org/notes/tn5/ >
Unicode Technical Standard #10: Unicode Collation Algorithm , available at <https://unicode.org/reports/tr10/ >
Unicode Standard Annex #15, Unicode Normalization Forms , available at <https://unicode.org/reports/tr15/ >
Unicode Standard Annex #18: Unicode Regular Expressions , available at <https://unicode.org/reports/tr18/ >
Unicode Standard Annex #24: Unicode Script Property , available at <https://unicode.org/reports/tr24/ >
Unicode Standard Annex #31, Unicode Identifiers and Pattern Syntax , available at <https://unicode.org/reports/tr31/ >
Unicode Standard Annex #44: Unicode Character Database , available at <https://unicode.org/reports/tr44/ >
Unicode Technical Standard #51: Unicode Emoji , available at <https://unicode.org/reports/tr51/ >
IANA Time Zone Database , available at <https://www.iana.org/time-zones >
ISO 8601:2004(E) Data elements and interchange formats — Information interchange — Representation
of dates and times
RFC 1738 “Uniform Resource Locators (URL)” , available at <https://tools.ietf.org/html/rfc1738 >
RFC 2396 “Uniform Resource Identifiers (URI): Generic Syntax” , available at <https://tools.ietf.org/html/rfc2396 >
RFC 3629 “UTF-8, a transformation format of ISO 10646” , available at <https://tools.ietf.org/html/rfc3629 >
RFC 7231 “Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content” , available at <https://tools.ietf.org/html/rfc7231 >
Colophon
This specification is authored on GitHub in a plaintext
source format called Ecmarkup . Ecmarkup is an HTML
and Markdown dialect that provides a framework and toolset for authoring ECMAScript specifications in
plaintext and processing the specification into a full-featured HTML rendering that follows the
editorial conventions for this document. Ecmarkup builds on and integrates a number of other formats and
technologies including Grammarkdown for defining
syntax and Ecmarkdown for authoring algorithm steps.
PDF renderings of this specification are produced using a print stylesheet which takes advantage of the
CSS Paged Media specification and is converted using PrinceXML .
Prior editions of this specification were authored using Word—the Ecmarkup source text that formed the
basis of this edition was produced by converting the ECMAScript 2015 Word document to Ecmarkup using an
automated conversion tool.
Copyright & Software License
Ecma International
Rue du Rhone 114
CH-1204 Geneva
Tel: +41 22 849 6000
Fax: +41 22 849 6001
Web: https://ecma-international.org/
Copyright Notice
© 2025 Ecma International
This draft document may be copied and furnished to others, and derivative works that comment on or
otherwise explain it or assist in its implementation may be prepared, copied, published, and
distributed, in whole or in part, without restriction of any kind, provided that the above copyright
notice and this section are included on all such copies and derivative works. However, this document
itself may not be modified in any way, including by removing the copyright notice or references to
Ecma International, except as needed for the purpose of developing any document or deliverable
produced by Ecma International.
This disclaimer is valid only prior to final version of this document. After approval all rights on
the standard are reserved by Ecma International.
The limited permissions are granted through the standardization phase and will not be revoked by Ecma
International or its successors or assigns during this time.
This document and the information contained herein is provided on an "AS IS" basis and ECMA
INTERNATIONAL DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY
WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY
IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
Software License
All Software contained in this document ("Software") is protected by copyright and is being made
available under the "BSD License", included below. This Software may be subject to third party rights
(rights from parties other than Ecma International), including patent rights, and no licenses under such
third party rights are granted under this license even if the third party concerned is a member of Ecma
International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm
FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA
INTERNATIONAL STANDARDS.
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
Neither the name of the authors nor Ecma International may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.